CHips L MINI SHELL

CHips L pro

Current Path : /opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/lib/RVSGL/rvsLibs/
Upload File :
Current File : //opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/lib/RVSGL/rvsLibs/WysiwygPro.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 WYSIWYG PRO libary
 *
 * @package RvsLibs
 * @author  Pairote Manunphol <pairote@rvglobalsoft.com>
 * @version $Revision$
 * @since   PHP 5.1
*/

if (!defined('WYSIWYG_ROOT_PATH')) {
define('WYSIWYG_ROOT_PATH', SGL_PATH . '/www/wysiwyg');
}

//problem da setup.raw SGL::logMessage
//SGL::logMessage("WYSIWYG_ROOT_PATH = " . WYSIWYG_ROOT_PATH, PEAR_LOG_DEBUG);

include_once(WYSIWYG_ROOT_PATH . "/editor_functions.php");
include_once(WYSIWYG_ROOT_PATH . "/wysiwygPro.class.php");
if (class_exists('RvsLibs_WysiwygPro') === false) {
	class RvsLibs_WysiwygPro
	{
		public static function WysiwygPro($aParams, $bridge)
		{
			/// Load config.bridge.php
			if (is_null($bridge) === true) {
				/// bridge for RVSiteBuilder Project
				include_once(WYSIWYG_ROOT_PATH . "/config.bridge.php");
			} else {
				include_once($bridge);
			}
			return  new wysiwygPro();
		}

		public static function setWysiwygOpts(&$oWysiwyg, $aParams, $aPluginConfWysi = array())
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			foreach ($aParams as $k => $av) {
				switch ($k) {
					case 'properties': RvsLibs_WysiwygPro::_setWysiwygProperties($oWysiwyg, $av);  break;
					case 'rvsImageLibrary':RvsLibs_WysiwygPro::_setRvsImageLibrary($oWysiwyg, $av);break;
					case 'rvsMediaLibrary':RvsLibs_WysiwygPro::_setRvsMediaLibrary($oWysiwyg, $av);break;
					case 'addStyle':RvsLibs_WysiwygPro::_setAddStyle($oWysiwyg, $av); break;
					case 'addFont': RvsLibs_WysiwygPro::_setAddFont($oWysiwyg, $av);break;
					case 'addSize':RvsLibs_WysiwygPro::_setAddSize($oWysiwyg, $av);break;
					case 'removeSize':RvsLibs_WysiwygPro::_setRemoveSize($oWysiwyg, $av); break;
					case 'addRegisteredButton' :RvsLibs_WysiwygPro::_setAddRegisteredButton($oWysiwyg, $av); break;
					case 'registerButton' :RvsLibs_WysiwygPro::_setRegisterButton($oWysiwyg, $av);break;
					case 'addContextMenuItem' : RvsLibs_WysiwygPro::_setAddContextMenuItem($oWysiwyg, $av);break;
					case 'registerSelect' :RvsLibs_WysiwygPro::_setRegisterSelect($oWysiwyg, $av);break;
					case 'registerDropdown' :RvsLibs_WysiwygPro::_setregisterdropdown($oWysiwyg, $av); break;
					case 'registerButtonDropdown' :RvsLibs_WysiwygPro::_setregisterdropdown($oWysiwyg, $av); break;
					case 'registerlayout' :RvsLibs_WysiwygPro::_setregisterlayout($oWysiwyg, $av); break;
					case 'addseparator' : RvsLibs_WysiwygPro::_setAddseparator($oWysiwyg, $av);break;
					case 'addbutton' : RvsLibs_WysiwygPro::_setAddbutton($oWysiwyg, $av);break;
					case 'toolbarLayoutGroup' :RvsLibs_WysiwygPro::_setaToolbarLayoutGroup($oWysiwyg, $av);reak;
					case 'toolbarLayout' :RvsLibs_WysiwygPro::_setaToolbarLayout($oWysiwyg, $av); break;
					case 'addNewGroup' :RvsLibs_WysiwygPro::_setaddNewGroup($oWysiwyg, $av); break;
					case 'aGroup' :  RvsLibs_WysiwygPro::_setaGroup($oWysiwyg, $av); break;
				}
			}

			if( isset( $aPluginConfWysi ) && $aPluginConfWysi != '') {
				$oWysiwyg = &$oWysiwyg;
				RvsLibs_WysiwygPro::_setaParamsConf($oWysiwyg,$aPluginConfWysi);
			}

			return $oWysiwyg;
		}
		private static function _setaParamsConf(&$oWysiwyg, $aConfPlugin)
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			foreach ($aConfPlugin as $k => $av) {
				switch ($k) {
					case 'properties': RvsLibs_WysiwygPro::_setWysiwygProperties($oWysiwyg, $av); break;
					case 'rvsImageLibrary': RvsLibs_WysiwygPro::_setRvsImageLibrary($oWysiwyg, $av);break;
					case 'rvsMediaLibrary':RvsLibs_WysiwygPro::_setRvsMediaLibrary($oWysiwyg, $av);break;
					case 'addStyle': RvsLibs_WysiwygPro::_setAddStyle($oWysiwyg, $av);break;
					case 'addFont':RvsLibs_WysiwygPro::_setAddFont($oWysiwyg, $av); break;
					case 'addSize': RvsLibs_WysiwygPro::_setAddSize($oWysiwyg, $av);break;
					case 'removeSize':RvsLibs_WysiwygPro::_setRemoveSize($oWysiwyg, $av);break;
					case 'addRegisteredButton' :RvsLibs_WysiwygPro::_setAddRegisteredButton($oWysiwyg, $av);break;
					case 'registerButton' :RvsLibs_WysiwygPro::_setRegisterButton($oWysiwyg, $av);break;
					case 'addContextMenuItem' : RvsLibs_WysiwygPro::_setAddContextMenuItem($oWysiwyg, $av); break;
					case 'registerSelect' : RvsLibs_WysiwygPro::_setRegisterSelect($oWysiwyg, $av);break;
					case 'addseparator' : RvsLibs_WysiwygPro::_setAddseparator($oWysiwyg, $av);break;
					case 'addbutton' : RvsLibs_WysiwygPro::_setAddbutton($oWysiwyg, $av); break;
					case 'toolbarLayoutGroup' : RvsLibs_WysiwygPro::_setaToolbarLayoutGroup($oWysiwyg, $av);break;
					case 'toolbarLayout' : RvsLibs_WysiwygPro::_setaToolbarLayout($oWysiwyg, $av);break;
					case 'addNewGroup' :RvsLibs_WysiwygPro::_setaddNewGroup($oWysiwyg, $av); break;
					case 'aGroup' : RvsLibs_WysiwygPro::_setaGroup($oWysiwyg, $av); break;
				}
			}
		}
		private static function _setWysiwygProperties(&$oWysiwyg, $av = array())
		{
			if(empty($thisConf)) {
				$c = SGL_Config::singleton();
				$thisConf = $c->getAll();
			}
			foreach ($av as $k => $v) {
				switch ($k)
				{
					case 'name':
						$oWysiwyg->set_name($v);
						break;
					case 'height':
						$oWysiwyg->height = $v;
						break;
					case 'width':
						$oWysiwyg->width = $v;
						break;
					case 'saveSrc':
                        $oWysiwyg->saveSrc = $v;
                        break;
					case 'disableFeatures' :
						$aEnableFea = RvsLibs_String::mb_split(",", $v);
						if (is_array($aEnableFea) === true) {
							foreach ($aEnableFea as $ev) {;
							$oWysiwyg->$k($ev);
							}
						}
						break;
					case 'loadmethod':
					case 'maxDocSize':
						$oWysiwyg->maxDocSize = (isset($thisConf['wysiwyg']['maxUploadDocumentFile']))
						? RvsLibs_String::trim($thisConf['wysiwyg']['maxUploadDocumentFile'])
						: $v;
						break;
					case 'maxImageSize':
						$oWysiwyg->maxImageSize = (isset($thisConf['wysiwyg']['maxUploadImageFile']))
						? RvsLibs_String::trim($thisConf['wysiwyg']['maxUploadImageFile'])
						: $v;
						break;
					case 'maxMediaSize':
						$oWysiwyg->maxMediaSize = (isset($thisConf['wysiwyg']['maxUploadMediaFile']))
						? RvsLibs_String::trim($thisConf['wysiwyg']['maxUploadMediaFile'])
						: $v;
						break;
					case 'allowedDocExtensions':
						$oWysiwyg->allowedDocExtensions = (isset($thisConf['wysiwyg']['documentFileType']))
						? RvsLibs_String::trim($thisConf['wysiwyg']['documentFileType'])
						: $v;
						break;
					case 'allowedMediaExtensions':
						$oWysiwyg->allowedMediaExtensions = (isset($thisConf['wysiwyg']['mediaFileType']))
						? RvsLibs_String::trim($thisConf['wysiwyg']['mediaFileType'])
						: $v;
						break;
					case 'removebuttons':
						foreach ($v as $ev) {
							$oWysiwyg->removeButtonsRvs($ev);
						}
						break;
					case 'addStylesheet':
						foreach ($v as $ev) {
							$oWysiwyg->addStyleSheetRvs($ev);
						}
						break;
					case 'addCSSText':
						$oWysiwyg->addCSSText($v);
						break;
					case 'addRegisteredButton':
						foreach ($v as $k=>$ev) {
							$oWysiwyg->addRegisteredButtonRvs($k,$ev);
						}
						break;
					case 'set_instance_lang':

					case 'enableFeature':
						$aEnableFea = RvsLibs_String::mb_split(",", $v);
						if (is_array($aEnableFea) === true) {
							foreach ($aEnableFea as $ev) {
								$oWysiwyg->$k($ev);
							}
						}
						break;
					case 'loadPlugin':
						$aLoadPlugin = RvsLibs_String::mb_split(",", $v);
						if (is_array($aLoadPlugin) === true) {
							foreach ($aLoadPlugin as $ev) {
								$oWysiwyg->$k($ev);
							}
						}
						break;
					default :
						if(defined('PROJECT_ID')){
							$oWysiwyg->$k = str_replace('#PROJECT_ID#',PROJECT_ID,$v);
						}else {
							$oWysiwyg->$k = str_replace('#PROJECT_ID#',SGL_Session::get('rvs_project_id'),$v);
						}
				}
			}
		}

		private static function _setRvsImageLibrary(&$oWysiwyg, $av = array())
		{
			$aOptImageLibrary = new wproDirectory();
			foreach ($av as $k => $v) {
				$aOptImageLibrary->$k = $v;
			}
			$oWysiwyg->addDirectory($aOptImageLibrary);
		}

		private static function _setRvsMediaLibrary(&$oWysiwyg, $av = array())
		{
			$aOptMediaLibrary = new wproDirectory();
			foreach ($av as $k => $v) {
				$aOptMediaLibrary->$k = $v;
			}
			$oWysiwyg->addDirectory($aOptMediaLibrary);
		}

		private static function _setAddStyle(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->addStyle($v, $k);
			}
		}

		private static function _setAddFont(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->addFont($k, $v);
			}
			// ===  font custom

			$fileFontIni =  RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder', 'customfont','fontname.ini.php'));
			if(is_file($fileFontIni)){
				include $fileFontIni;
				if (isset($aFontCustom) && count($aFontCustom) > 0) {
					foreach ($aFontCustom as $k => $v) {
						$aFontCustom[$k] = RvsLibs_String::ucfirst($aFontCustom[$k]);
						$oWysiwyg->addFont($aFontCustom[$k], $aFontCustom[$k]);
					}
				}
			}


		}

		private static function _setRemoveSize(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k) {
				$oWysiwyg->removeSize($k);
			}
		}

		private static function _setAddSize(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->addSize($v, $k);
			}
		}

		private static function _setAddRegisteredButton(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->addRegisteredButtonRvs($k, $v);
			}
		}
		/**********************************************
		 * add by darawan 02/11/52
		 * $oEditor->registerButton($idname, $tooltip, $function, $url, $width=22, $height=22, $cid = '', $textButton=false)
		 ***********************************************/
		private static function _setRegisterButton(&$oWysiwyg, $av = array())
		{
			foreach($av as $k => $v){
				$oWysiwyg->registerButton($k,$v['tooltip'],$v['function'],$v['url'],$v['width'],$v['height'],$v['cid'],$v['textButton']);
			}
		}

		private static function _setAddContextMenuItem(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->addContextMenuItem($k, $v);
			}
		}

		private static function _setRegisterSelect(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->registerSelect('.$k.',' . join(',' , $v). ');
			}
		}
		private static function _setregisterButtonDropdown(&$oWysiwyg, $av = array()) {

		 foreach($av as $k => $v){
                $oWysiwyg->registerButtonDropdown($k,$v['tooltip'],$v['function'],$v['url'],$v['width'],$v['height'],$v['cid'],$v['textButton']);
            }
		}
		//_setregisterdropdown
		private static function _setregisterdropdown(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->registerdropdown($k, $v);
			}
		}

		// registerlayout on wysi:nipaporn
	    private static function _setregisterlayout(&$oWysiwyg, $av = array())
        {
            foreach ($av as $k => $v) {
                $oWysiwyg->registerlayout($k, $v);
            }
        }

		private static function _setAddseparator(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->addseparator($k, $v);
			}
		}

		private static function _setAddbutton(&$oWysiwyg, $av = array())
		{
			foreach ($av as $k => $v) {
				$oWysiwyg->addbutton($k, $v);
			}
		}

		/**********************************************
		 * $oEditor->toolbarLayoutGroup add by darawan 02/11/52
		 * $oEditor->toolbarLayoutGroup = array(
		 *		'toolbar1'=>array
		 * 			(
		 *				'save','view','link','pagelink','upload','editorText','Add-on'
		 *       	),
		 *		'toolbar2'=>array('font','style','FontStyle','table','alignment','IdenAndList'),
		 *  );
		 ***********************************************/
		private static function _setaToolbarLayoutGroup(&$oWysiwyg, $av = array())
		{
			$oWysiwyg->toolbarLayoutGroup = $av;
		}

		/**********************************************
		 * $oEditor->toolbarLayout add by darawan 02/11/52
		 * $oEditor->toolbarLayout = array(
		 *		'save' => array('wys_save_back','wys_save_page'),
		 *		'view' => array('fullwindow','find','undo','redo')
		 *  );
		 ***********************************************/
		private static function _setaToolbarLayout(&$oWysiwyg, $av = array())
		{
			$oWysiwyg->toolbarLayout = $av;
		}

		/***********************************************
		 * $oEditor->addNewGroup add by darawan 02/11/52
		 * $oEditor->addNewGroup('setGroupName',array('font','style','fontstyle')),
		 ***********************************************/
		private static function _setaddNewGroup(&$oWysiwyg, $av = array())
		{
			foreach($av as $k=>$v){
				$oWysiwyg->addNewGroupRvs($k,$v);
				// echo '<br>$oWysiwyg->addNewGroupRvs('.$k.','.$v.')';
			}
		}

		/***********************************************
		 * $oEditor->aGroup add by darawan 02/11/52
		 * $oEditor->aGroup = array('save'=>array('name'=>'ชื่อ กล่ม'
		 * 						,'display'=>array('class'=>'wys-block')),
		 ***********************************************/
		private static function _setaGroup(&$oWysiwyg, $av = array())
		{
			// 'save'=>array('name'=>'','display'=>array('class'=>'wys-block')),
			if(isset($av) && $av != '') {
				if( isset( $av['class'] ) && $av['class'] != '' ) {
					$classDef = $av['class'];
					unset($av['class']);
				} else $classDef = 'wys-block';

				foreach ($av as $k => $v) {
					if(!isset($v['display']) && empty($v['display'])) {
						$av[$k]['display'] = array('class'=>$classDef);
					}
				}
				$oWysiwyg->aGroup = $av;
			}
		}

		/**
		 * removeTags
		 * @todo  remove tag html code
		 * @param string $htmlcode
		 * @param array $aRemoveTage
		 * @return string
		 */
		public static function removeTags($htmlcode, $aRemoveTage)
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			return remove_tags($htmlcode, $aRemoveTage);
		}

		/**
		 *
		 * @param unknown_type $htmlcode
		 * @return unknown_type
		 */
		public static function disableTagsPhp($htmlcode)
		{
			return disable_tags_php($htmlcode);
		}

		/**
		 * comment2php
		 *@todo Converts comments back to PHP
		 * @param string $htmlcode
		 * @return string
		 */
		public static function comment2php($htmlcode)
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			return comm2php($htmlcode);
		}
		/**
		 * removeTagForWysiwyg
		 *
		 * @param string $htmlcode
		 * @return array $aData
		 */
		public static function removeTagForWysiwyg($htmlcode,$aTemplateData)
		{
			$htmlcode =  preg_replace('#<\s*(\/?)\s*html[^>]*?>#si' , "" , $htmlcode);
			$htmlcode =  preg_replace('#<\!DOCTYPE[^>]*?>#si' , "" , $htmlcode);
			$htmlcode =  preg_replace('#<\s*(\/?)\s*head[^>]*?>#si' , "" , $htmlcode);
			$htmlcode =  preg_replace('#<\s*(\/?)\s*title[^>]*?>((?!<title).*?)</title[^>]*>#si' , "" , $htmlcode);
			$htmlcode =  preg_replace('#<\s*\?\s*xml[^>]*?>#si' , "" , $htmlcode);
			$htmlcode =  preg_replace('#<\s*\s*meta[^>]*\/>#si' , "" , $htmlcode);
			// remove <body>  on $htmlcode แล้ว event ที่มีอยู่บน body นี้ทั้งหมดจะต้อง export ไปยัง display()
			//                เพื่อส่งต่อไป build ใน header.html ได้
			preg_match('#<\s*body([^>]*?)>#si' ,$htmlcode ,$aMatches);
			$aMatches[1] = preg_replace('#(.*)\/\s*$#', "$1", $aMatches[1]);
			$htmlcode =  preg_replace('#<\s*(\/?)\s*body[^>]*?>#si' , "" , $htmlcode);

			// remove <link ...>  on $htmlcode แล้ว export ไปยัง display()
			//                เพื่อส่งต่อไป build ใน header.html ได้
			preg_match_all('#<\s*link[^>]*?>#si' ,$htmlcode ,$aHeadMatches);
			$htmlcode = preg_replace('#<\s*link[^>]*?>#si' ,'',$htmlcode);
			$aData = array();
			$aData['htmlcode'] = $htmlcode;
			$aData['templateBodyElements'] = trim($aMatches[1]);
			$aData['headElemnts'] = '';
			$projectId = RvsLibs_Project::getProjectId();
            $isResponsive = RvsLibs_Template::isResponsiveTemplate($aTemplateData->templatePath . '/' . $aTemplateData->template_item_folder);
            if ($isResponsive) {
            	$defaultCss = 'layout.css';
            	$customCss = 'custom_layout.css';
            } else {
            	$defaultCss = 'style.css';
            	$customCss = $defaultCss;
            }
			$pattern = '#href\s*=\s*[\'"][^"]*/' . $defaultCss . '[\'" >]#si';
			$patternCustomCss = '#href\s*=\s*[\'"][^"]*/customcss/' . $customCss . '[\'" >]#si';
            foreach ($aHeadMatches[0] as $val) {
				if(preg_match($pattern, $val)){

					/* ========================================START add file css ustomcss : nipaporn ================================================*/
					if(preg_match($patternCustomCss, $val)){
						$customCssPath = RvsLibs_Project::validateCustomCssPath($projectId, $aTemplateData->template_item_folder);
						$fileCustomPath =  RvsLibs_File::buildPath(array(
							$customCssPath, $customCss
						));
						if (is_file($fileCustomPath) === true) {
							$aPageCss = RvsLibs_File::file($fileCustomPath);
							$strPageCss = join("", $aPageCss);
						}
					} else {
					   $aPageCss = RvsLibs_File::file($aTemplateData->templatePath . '/' . $aTemplateData->template_item_folder . '/' . $defaultCss);
					   $strPageCss = join("", $aPageCss);
					}
                    /* ========================================END add file css ustomcss : nipaporn ================================================*/

					# Fix image path
					$strPageCss = preg_replace('#url\s*\(images/(.*?)\)#si' ,
        	                 "url(" . $aTemplateData->templateUrl . '/' . $aTemplateData->template_item_folder . "/images/$1)" ,
					$strPageCss);
					# remove body class
					$strPageCss = preg_replace('/(\}?)\s*\bbody\b\s*\{([^}]*)\}/is' ,
                             "$1" ,
					$strPageCss);

					$aData['headElemnts'] .= '<style type="text/css">'.$strPageCss . "</style>\n";

				}else{
					$aData['headElemnts'] .= $val . "\n";
				}
			}
			return $aData;
		}

		public static function removeInavalidTags($htmlcode)
		{
			$htmlcode =  preg_replace('#<\s*\?\s*xml[^>]*?>#si' , "" , $htmlcode);
			$htmlcode =  preg_replace('#<\s*(\/?)\s*html[^>]*?>#si' , "" , $htmlcode);
			$htmlcode =  preg_replace('#<\s*(\/?)\s*body[^>]*?>#si' , "" , $htmlcode);

			/*Except or allow tag case by case:
			 <fb:comments></fb:comments>
			 <gcse:search></gcse:search>
			 <g:????></g:????>
			 */
			$htmlcode = preg_replace('#(</?)fb:#i' , "$1fb__RVCOLON__" , $htmlcode);
			$htmlcode = preg_replace('#(</?)g:#i' , "$1g__RVCOLON__" , $htmlcode);
			$htmlcode = preg_replace('#(</?)gcse:#i' , "$1gcse__RVCOLON__" , $htmlcode);

			 /*Remove tag <{string}:{string}>....</string> in wysiwyg
             <o:left v:ext="view" color="black [0]" color2="white [7]"></o:left>
             <o:top v:ext="view" color="black [0]" color2="white [7]"></o:top>
             <o:right v:ext="view" color="black [0]" color2="white [7]"></o:right>
             <o:bottom v:ext="view" color="black [0]" color2="white [7]"></o:bottom>
             <o:column v:ext="view" color="black [0]" color2="white [7]"></o:column>
            */
			$htmlcode = preg_replace('#<([a-zA-Z0-9]+):[^>]*?>((?!<\1).*?)</\1:[^>]*>#si' , "$2" , $htmlcode);

			# <o:left v:ext="view" color="black [0]" color2="white [7]">
			# <o:left v:ext="view" color="black [0]" color2="white [7]">

			$htmlcode = preg_replace('#<[a-zA-Z0-9]+:[^>]*?>#s' , '' , $htmlcode);
			//don't work
			/*$htmlcode = preg_replace('#<xml[^>]*?>((?!<xml).*?)</xml:[^>]*>#si' , "" , $htmlcode);*/
            /*
             * remove
             * <xml ??????> ??????????? </xml>
             */
			$htmlcode = preg_replace('#<xml.*?>(.*?)</xml>#si' , "" , $htmlcode);
            /*
             * remove <![endif]--><!--[if gte mso 9]>
             */
			$htmlcode = preg_replace('#<\!\-\-\[(.*?)\]>|<\!\[endif\]\-\->#si',"",$htmlcode);
			$htmlcode = preg_replace('#__RVCOLON__#' , ":" , $htmlcode);
			return $htmlcode;
		}

		public static function validateHtmlTag($pageData)
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			$tag['validate'] = true;
			$tagBody = '/<\s*body/i';
			$tagBodyClose = '/<\s*\/\s*body/i';
			$tagXml = '/<\s*\?\s*xml/i';
			$tagHtml = '/<\s*html/i';
			$tagHtmlClose = '/<\s*\/\s*html/i';
			$tagHead = '/<\s*head/i';
			$tagHeadClose = '/<\s*\/\s*head/i';

			if (preg_match($tagBody, $pageData)) {
				$tag['validate'] = false;
				$tag['body'] = true;
			}

			if (preg_match($tagBodyClose, $pageData)) {
				$tag['validate'] = false;
				$tag['bodyClose'] = true;
			}

			if (preg_match($tagXml, $pageData)) {
				$tag['validate'] = false;
				$tag['xml'] = true;
			}

			if (preg_match($tagHtml, $pageData)) {
				$tag['validate'] = false;
				$tag['html'] = true;
			}

			if (preg_match($tagHtmlClose, $pageData)) {
				$tag['validate'] = false;
				$tag['htmlClose'] = true;
			}

			if (preg_match($tagHead, $pageData)) {
				$tag['validate'] = false;
				$tag['head'] = true;
			}

			if (preg_match($tagHeadClose, $pageData)) {
				$tag['validate'] = false;
				$tag['headClose'] = true;
			}
			return $tag;
		}

		/**
		 * this function list all pagestructure mainpage subpage and internal page
		 * use in wysiwyg insert hyperlink project  pagestructure
		 *
		 * @return <array> unknown
		 */
		public static function getWysRvsPageLink()
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$oMgr = SGL_Manager::singleton();
			$usrId = RvsLibs_WysiwygPro::getRvsUsrIdForWysiwyg();
			$ownerUsrId = RvsLibs_WysiwygPro::getRvsOwnerUsrIdForWysiwyg();
			$projectID = RvsLibs_Project::getProjectId();
			$pageStructure = RvsLibs_Project::getPageStructureData($projectID , $usrId, $ownerUsrId);
			$internalPageStructure = RvsLibs_Project::getInternalPageData($projectID, $usrId);
			$confAllowPHP = $oMgr->conf['wysiwyg']['allowPhp'];
			$i = 0;

			if (isset($pageStructure['aPageName'])) {
				unset($pageStructure['aPageName']);
			}

			//จัดโครงสร้าง index = page_id
			foreach ($pageStructure as $key => $value) {
				$pageStructure[$value->project_page_id] = $pageStructure[$key];
			}

			// generate menu to 2 level
			$aPageStructure = RvsLibs_Project::getPageStructureLevel2($pageStructure);

			$aLink = DaoFactory::Link()->findAllLinkByProject($projectID, 'getAssoc');
			//echo '<pre>';print_r($aLink);exit;

			foreach ($aPageStructure as $key => $value) {

				///get link data by link_id
				if (isset($aLink[$value->project_page_id])) {
					$wysRvsPageLink[$i]['external_url'] = $aLink[$value->project_page_id]->external_url;
				} else {
					$wysRvsPageLink[$i]['external_url'] = '';
				}

				$component = $value->rvs_component_id;
				$pageExtension = RvsLibs_File::getPageExtension($component, $value->project_page_id, $confAllowPHP);

				//Main
				$wysRvsPageLink[$i]['title'] = RvsLibs_String::brToNewline($value->page_name,"<br />");
				$wysRvsPageLink[$i]['URL'] = $value->project_page_id . '.' . $pageExtension;
				$wysRvsPageLink[$i]['pageId'] = $value->project_page_id;
				$i++;

				//gen sub level1
				if (isset($value->level1)) {
					foreach ($value->level1 as $k1 => $v1) {
						if (isset($aLink[$v1->project_page_id])) {
							$wysRvsPageLink[$i]['external_url'] = $aLink[$v1->project_page_id]->external_url;
						} else {
							$wysRvsPageLink[$i]['external_url'] = '';
						}
						$sub2 = ($v1->parent_project_page_id != '0') ? '>' : '';
						$wysRvsPageLink[$i]['title'] = $sub2 . RvsLibs_String::brToNewline($v1->page_name,"<br />");
						$wysRvsPageLink[$i]['URL'] = $v1->project_page_id . '.' . $pageExtension;
						$wysRvsPageLink[$i]['pageId'] = $v1->project_page_id;
						$i++;

						//gen sub level2
						if (isset($v1->level2)) {
							foreach ($v1->level2 as $k2 => $v2) {
								if (isset($aLink[$v2->project_page_id])) {
									$wysRvsPageLink[$i]['external_url'] = $aLink[$v2->project_page_id]->external_url;
								} else {
									$wysRvsPageLink[$i]['external_url'] = '';
								}
								$sub1 = ($v2->parent_project_page_id != '0') ? '>>' : '';
								$wysRvsPageLink[$i]['title'] = $sub1 . RvsLibs_String::brToNewline($v2->page_name,"<br />");
								$wysRvsPageLink[$i]['URL'] = $v2->project_page_id . '.' . $pageExtension;
								$wysRvsPageLink[$i]['pageId'] = $v2->project_page_id;
								$i++;
							}
						}//End level2
					}
				}//End level1
			}//End Main


			$j = 1;
			foreach ($internalPageStructure as $key=>$value) {
				if (isset($aLink[$value->project_page_id])) {
					$wysRvsPageLink[$i]['external_url'] = $aLink[$value->project_page_id]->external_url;
				} else {
					$wysRvsPageLink[$i]['external_url'] = '';
				}
				if ($j == 1) {
					$wysRvsPageLink[$i]['title'] = "--------- Internal Page ---------";
					$i++;
				}
				$component = $value->rvs_component_id;
				$pageExtension = RvsLibs_File::getPageExtension($component, $value->project_page_id, $confAllowPHP);
				$wysRvsPageLink[$i]['title'] = RvsLibs_String::brToNewline($value->page_name,"<br />");
				$wysRvsPageLink[$i]['URL'] = $value->project_page_id . '.' . $pageExtension;
				$wysRvsPageLink[$i]['pageId'] = $value->project_page_id;
				$i++;
				$j++;
			}
			return $wysRvsPageLink;
		}

		public static function getRvsUsrIdForWysiwyg()
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$rvsUserName = RVS_USER_NAME;
			$res = DaoFactory::Usr()->findUsrIdByUsername($rvsUserName, 'getrow');
			if ($res) {
				$rvsUsrId = $res['rvs_usr_id'];
			} else {
				$rvsUsrId = RvsLibs_String::genUniqueId();
				$res = DaoFactory::Usr()->insertUsr($rvsUsrId, $rvsUserName);
				// get rvs_user_id;
				$rvsUsrId = mysql_insert_id();
			}
			return $rvsUsrId;
		}

		public static function getRvsOwnerUsrIdForWysiwyg()
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);

			$rvsOwnerName = RVS_OWNER_USER_NAME;
			$rvsOwnerId = 0;
			$res = DaoFactory::Usr()->findUsrIdByUsername($rvsOwnerName, 'getrow', array());
			if ($res) {
				$rvsOwnerId = $res['rvs_usr_id'];
			} else {
				$rvsUsrId = RvsLibs_String::genUniqueId();
				$res = DaoFactory::Usr()->insertUsr($rvsUsrId, $rvsOwnerName);
				$rvsOwnerId = mysql_insert_id();
			}
			return $rvsOwnerId;
		}

		public static function replaceBody($aPageBody, $defaultPageData, $rvsComponentId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			/* Body */
			$aPageBodyData = "";
			if ($aPageBody) {
				// DB PageData
				$aPageBodyData .= $aPageBody;
			} else {
				if (($rvsComponentId != 0 || $rvsComponentId != '0' || $rvsComponentId == '' ) && $defaultPageData != '') {
					// Component PageData
					$aPageBodyData .= $defaultPageData;
				} else {
					if (!RvsLibs_Config::isNoLayoutTemplste() && $defaultPageData != '') {
						// Layout PageData
						$aPageBodyData .= $defaultPageData;
					} else {
						$aPageBodyData .= "<p>" . SGL_String::translate('Your text start HERE...') . "</p>";
					}
				}
			}
			$aPageBodyData = RvsLibs_String::removeCssFullURLWithPort($aPageBodyData);
			return $aPageBodyData;
		}


		/**
		 * $aMatch = array(
		 * '0' => array('0'=>'AAAAA', '1'=>'BBBB'), //string match
		 * '1' => array('0'=>'AAAAA', '1'=>'BBBB'), //mime type
		 * '2' => array('0'=>'AAAAA', '1'=>'BBBB'), //encode type base64
		 * '3' => array('0'=>'AAAAA', '1'=>'BBBB'), //content file encoder
		 * )
		 */
		public static function getInlineImgData($HTMLCode)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
            //กรณีที่ data ที่เข้ามา match มีความยาวมากมาก จะต้อง ini_set 2 ค่านี้ด้วย
            //ถ้าส่วนเจอปัญหาค่อยย้ายไปไว้ใน Process.php/SGL_Task_Init นะคับ
			@ini_set('pcre.backtrack_limit', 20000000);
			@ini_set('pcre.recursion_limit', 20000000);
            //TODO <img([^>].*?)src\s*=\s*"data:(.*?);(.*?),(.*?)"/simx patten นี้ถ้ามีการแทรกรูปที่ไม่ใช่ inlineimage เข้ามาด้วย จะผิด
            $HTMLCode = str_replace('\"', '"', $HTMLCode);
			if (preg_match_all('/src\s*=\s*"data:(.*?);(.*?),(.*?)"/sim', trim($HTMLCode), $aMatch)) {
				return $aMatch;
			}
			return array();
		}

		/**
		 * convert inline image to md5 images
		 * save image to real project path /{id}/images
		 *
		 * @param $HTMLCode
		 * @param $projectId
		 * @return unknown_type
		 */
		public static function writeInlineImgToTmp($HTMLCode, $projectId=null)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$projectId = is_null($projectId)
				? RvsLibs_Project::getProjectId()
				: $projectId;
			if (SGL::isError($projectId)) {
				$projectId = null;
				SGL_Error::pop();
			}
			$tmpPath = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $projectId, 'images'));
			if (file_exists($tmpPath) === false) {
				$res = RvsLibs_System::mkDir(array('-p', '-m', 0755, $tmpPath));
				if (SGL::isError($res)) {
					//SGL::logMessage('creat tmp path Error:' . $tmpPath, PEAR_LOG_DEBUG);
					SGL_Error::pop();
					return $HTMLCode;
				}
			}

			/**
			 $aInlineImgData[0][0] = string line is match
			 $aInlineImgData[1][0] = string mimetype image/png , image/gif , image/jpeg
			 $aInlineImgData[2][0] = encode type base64
			 $aInlineImgData[3][0] = string encode of images
			 */
			$aInlineImgData = RvsLibs_WysiwygPro::getInlineImgData($HTMLCode);

            if (count($aInlineImgData) > 0) {
            	$fileName = '';
            	foreach ($aInlineImgData[3] as $k => $v) {
            		$fileExtension = RvsLibs_Image2::getExtOfMimeType(trim($aInlineImgData[1][$k]));
            		$fileContent = RvsLibs_Util::getDecodeByEncodeType(
            			trim($aInlineImgData[3][$k])
            			, trim($aInlineImgData[2][$k])
            		);
            		$aInlineImgData[3][$k] = preg_replace('/\s*/sim', '', $aInlineImgData[3][$k]);
            		$fileName = md5(trim($aInlineImgData[3][$k])) . '.' . $fileExtension;
            		//SGL::logMessage('ABC File name:' . $fileName . ' | mime type:' . $aInlineImgData[1][$k], PEAR_LOG_DEBUG);
            		if (file_exists($tmpPath . '/' . $fileName) === false) {
            			$handle = RvsLibs_File::writeFile($tmpPath . '/' . $fileName, $fileContent, 'w+');
            			if (SGL::isError($handle)) {
            				SGL_Error::pop();
            				continue;
            			}
            		}
                    // match \" = /\\\"/
            		if (preg_match_all('/\\\"/', $HTMLCode, $aMat)) {
            			//case replace SQL Data replace " to \"
            			$imgReplae = str_replace('"', '\"', trim($aInlineImgData[0][$k]));
            		} else {
            			//case nornmal from page data do not thing
            			$imgReplae = trim($aInlineImgData[0][$k]);
            		}
            		$HTMLCode = str_replace($imgReplae, 'src="{IMAGE_URL}/' . $fileName . '"', $HTMLCode);
            		//SGL::logMessage('ABC line:' . $HTMLCode, PEAR_LOG_DEBUG);
            	}
            }
            return $HTMLCode;
		}
	}
}
?>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez