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/SGL/Task/rvsUpdateDatabase.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: rvsUpdateDatabase.php ,v $Revision$ 24 ��.�. 2549 15:34:42 parinya Exp $
// +---------------------------------------------------------------------------+

/**
 * Short Description.
 * 
 * @package package_name
 * @author  Pairote Manunphol <pairote@rvskin.com>
 * @author  Parinya <parinya@rvglobalsoft.com>
 * @version $Revision$
 * @since   PHP 4.1
 */


class SGL_Task_rvsUpdateDatabase extends SGL_UpdateHtmlTask
{
    public function run($data=null)
    {
        
        require_once SGL_CORE_DIR . '/Sql.php';
        $c = SGL_Config::singleton();
        $this->conf = $c->getAll();
        $this->setup();
        $statusText = 'Update database';
        $this->updateHtml('status', $statusText);

        //  Print table shell, with module names; we'll update statuses as we execute sql below
        $out = '<h2>Update database</h2>';
        $out .= '<table class="inside">';
        $out .= '<tr>';
        $out .= '<th class="alignCenter">Module</th>';
        $out .= '<th class="alignCenter">New Module</th>';
        $out .= '<th class="alignCenter">Level</th>';
        $out .= '<th class="alignCenter">Update Schema</th>';
        $out .= '<th class="alignCenter">Update Default Data</th>';
        $out .= '<th class="alignCenter">Update Data</th>';
        $out .= '</tr>';

        if ( !(SGL::runningFromCli() || defined('SGL_ADMIN_REBUILD')) ) {
            echo($out);
        }

        foreach ($data['aModuleList'] as $module) {
            $out = '<tr>';
            $out .= '<td class="title">' . ucfirst($module) . '</td>';
            $out .= '<td id="' . $module . '_new" class="alignCenter"></td>';
            $out .= '<td id="' . $module . '_level" class="alignCenter"></td>';
            $out .= '<td id="' . $module . '_updateschema" class="alignCenter"></td>';
            $out .= '<td id="' . $module . '_updatedata" class="alignCenter"></td>';
            $out .= '<td id="' . $module . '_update" class="alignCenter"></td>';
            $out .= '</tr>';

            if (!(SGL::runningFromCli() || defined('SGL_ADMIN_REBUILD'))) {
                echo($out);
            }
        }
        
        //RVS information
        $out .= '<tr>';
        $out .= '<th colspan="6">Information</th>';
        $out .= '</tr>';
        $out .= '<tr>';
        $out .= '<td class="pageTitle" colspan="6">The system is redirecting you to your published website in a few seconds.<br />
If this takes too long, please wait a few minutes for the server load process, and try to publish again.<br />
If you still see this message after published twice and tried above suggestion, please try this <a href="https://rvglobalsoft.com/knowledgebase/article/127/cannot-publish-database-error/" target="_blank">solution</a>.</td>';
        $out .= '</tr>';
        if ( !(SGL::runningFromCli() || defined('SGL_ADMIN_REBUILD')) ) {
        	echo($out);
        }
        
        if ( !(SGL::runningFromCli() || defined('SGL_ADMIN_REBUILD'))) {
            echo('</table>');
            if ( !defined('SGL_NO_FLUSH') ) flush(); /// Don't flush if define SGL_NO_FLUSH [Parinya::20060624]
        }

        foreach ($data['aModuleList'] as $module) {
            $updataSitePath = SGL_MOD_DIR . '/' . $module . '/data';
            //echo $updataSitePath . '<br>';
            $lastUpdateLevel = (isset($this->conf['rvs_db_level'][$module])) ? $this->conf['rvs_db_level'][$module]: null;
            if ($lastUpdateLevel == null ) {
                if ( is_file($updataSitePath . $this->filename1) ) {
                	$result = SGL_Sql::parse($updataSitePath . $this->filename1, 0, array('SGL_Sql', 'execute'));
                    //$result = SGL_Sql::parseAndExecute($updataSitePath . $this->filename1, 0);
                }
                if ( is_file($updataSitePath . $this->filename2) && $result) {
                	$result = SGL_Sql::parse($updataSitePath . $this->filename2, 0, array('SGL_Sql', 'execute'));
                    //$result = SGL_Sql::parseAndExecute($updataSitePath . $this->filename2, 0);
                }
                if ( is_file($updataSitePath . $this->filename3) && $result) {
                	$result = SGL_Sql::parse($updataSitePath . $this->filename3, 0, array('SGL_Sql', 'execute'));
                    //$result = SGL_Sql::parseAndExecute($updataSitePath . $this->filename3, 0);
                }
                
                $displayHtml = (isset($result)) ? $this->success : $this->failure;
                $this->updateHtml($module . '_new', $displayHtml);
                
                if ( !isset($result) || !$result) {
                    continue;
                }
                $lastUpdateLevel = 1;
                $c->set('rvs_db_level', array($module => 1));
            } else if ( $lastUpdateLevel == 0 ) {
                $lastUpdateLevel = 1;
                $c->set('rvs_db_level', array($module => 1));
                $this->updateHtml($module . '_new', $this->noFile);
            } else {
                $this->updateHtml($module . '_new', $this->noFile);
            }
            
            $levelUpdate = (int)$lastUpdateLevel + 1;
            $StartlevelUpdate = $levelUpdate;
            while ( is_file($updataSitePath . '/update.my.' . $levelUpdate . '.sql') ||
                      is_file($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate1)) ||
                      is_file($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate2)) ) {
                
                if ( is_file($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate1)) ) {
                    $result = SGL_Sql::parse($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate1), 0, array('SGL_Sql', 'execute'));
                	//$result = SGL_Sql::parseAndExecute($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate1), 0);
                    $displayHtml = $result ? $this->success : $this->failure;
                    $this->updateHtml($module . '_updateschema', '<b>Level '. $levelUpdate . '</b>');
                } else {
                    $this->updateHtml($module . '_updateschema', $this->noFile);
                }
                
                
                if ( is_file($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate2)) ) {
                	$result = SGL_Sql::parse($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate2), 0, array('SGL_Sql', 'execute'));
                    //$result = SGL_Sql::parseAndExecute($updataSitePath . preg_replace('/\{x}/i', $levelUpdate, $this->fileupdate2), 0);
                    $displayHtml = $result ? $this->success : $this->failure;
                    $this->updateHtml($module . '_updatedata', '<b>Level '. $levelUpdate . '</b>');
                } else {
                    $this->updateHtml($module . '_updatedata', $this->noFile);
                }
                
                if ( is_file($updataSitePath . '/update.my.' . $levelUpdate . '.sql' ) ) {
                	//echo $updataSitePath . '/update.my.' . $levelUpdate . '.sql<br>';
                	$result = SGL_Sql::parse($updataSitePath . '/update.my.' . $levelUpdate . '.sql', 0, array('SGL_Sql', 'execute'));
                    //$result = SGL_Sql::parseAndExecute($updataSitePath . '/update.my.' . $levelUpdate . '.sql', 0);
                    //print_r($result);
                    $displayHtml = $result ? $this->success : $this->failure;
                    $this->updateHtml($module . '_update', '<b>Level '. $levelUpdate . '</b>');
                } else {
                    $this->updateHtml($module . '_update', $this->noFile);
                }
                
                $c->set('rvs_db_level', array($module => "$levelUpdate"));
                $levelUpdate++;
            }

            if ( $levelUpdate == $StartlevelUpdate ) {
                $this->updateHtml($module . '_level', $this->noFile);
                $this->updateHtml($module . '_updateschema', $this->noFile);
                $this->updateHtml($module . '_updatedata', $this->noFile);
                $this->updateHtml($module . '_update', $this->noFile);
            } else {
            	$updateTo = (int)$levelUpdate - 1;
            	if ($updateTo <> $StartlevelUpdate) {
            		$updateMsg = "$StartlevelUpdate - $updateTo";
            	} else {
            		$updateMsg = "$updateTo";
            	}
                $this->updateHtml($module . '_level', $updateMsg);
                $this->updateHtml($module . '_updateschema', $this->success);
                $this->updateHtml($module . '_updatedata', $this->success);
                $this->updateHtml($module . '_update', $this->success);
            }
        }
        $configFile = SGL_VAR_DIR . '/' . SGL_SERVER_NAME . '.conf.php';
        $ok = $c->save($configFile);
    }
}

class SGL_Task_rvsCheckingError extends SGL_UpdateHtmlTask
{
    public function run($data=null)
    {
    	$baseUrl = SGL_BASE_URL;
    	if (preg_match('/^http(|s):\/\/([^\/].*?)\/(.*)/', $baseUrl, $aMatch)) {    		
    		$aFor = explode('/', $aMatch[3]);
    		foreach ($aFor as $key => $val) {
    			$aFor[$key] = urlencode($val);
    		}
    		$baseUrl = 'http' . $aMatch[1] . '://' . $aMatch[2] . '/' . implode('/', $aFor);
    	}
        if ( !SGL_Install_Common::errorsExist()) {
            echo "\n". '<script>location.replace(\'' . $baseUrl . '/rvssetup.php?start\');</script>';
        }
    }   
}

/**
 * modify from lib/Task/Install.php SGL_Task_BuildNavigation
 * cannot detect $data['createTables'] == 1
 * and cannot detect $data['useExistingData'] == 0
 *
 */
class SGL_Task_rvsBuildNavigation extends SGL_UpdateHtmlTask
{
	var $groupId;
	var $childId;
    public function run($data = null)
    {
        if (SGL_Config::get('navigation.driver') != 'ArrayDriver') {
            require_once SGL_MOD_DIR . '/navigation/classes/NavigationDAO.php';
            $da = NavigationDAO::singleton();

            foreach ($data['aModuleList'] as $module) {
                $navigationPath = SGL_MOD_DIR . '/' . $module  . '/data/navigation.php';
                if (file_exists($navigationPath)) {
                    require_once $navigationPath;
                    if (isset($aSections) && count($aSections) > 0) {
                        foreach ($aSections as $aSection) {                            
                            //RVS Start remove before add navigation
                            //Copy from Install::SGL_Task_RemoveNavigation
                            $sectionId = $da->getSectionIdByTitle($aSection['title']);
                            if ($sectionId) {
                                $ok = $da->deleteSectionById($sectionId);
                            }
                            //RVS End remove
                            
                            //  check if section is designated as child to last insert
                            if ($aSection['parent_id'] == SGL_NODE_GROUP) {
                                $aSection['parent_id'] = $this->groupId;
                            }
                            $id = $da->addSimpleSection($aSection);
                            if (!SGL::isError($id)) {
                                if ($aSection['parent_id'] == SGL_NODE_ADMIN
                                        || $aSection['parent_id'] == SGL_NODE_USER) {
                                    $this->groupId = $id;
                                } else {
                                    $this->childId = $id;
                                }
                            } else {
                                SGL_Install_Common::errorPush($id);
                            }
                        }
                    }
                }
            }
        } elseif (SGL_Config::get('navigation.driver') == 'ArrayDriver') {
            require_once SGL_MOD_DIR . '/navigation/classes/ArrayDriver.php';

            $aNodes = ArrayDriver::getNavigationStructure();
            $ok = ArrayDriver::saveNodes($aNodes);
            if (!$ok) {
                SGL::raiseError('ArrayDriver: can\'t save nodes');
            }
        }
    } 
}

class SGL_Task_rvsClearCache extends SGL_UpdateHtmlTask
{
	public function run($data=null)
	{
	     require_once 'System.php';
		foreach ($data['aModuleList'] as $module) {
		    switch (strtolower($module)) {
		        case 'default' :
		            if (defined('SGL_VAR_DIR')) {
		                $tmpDir = SGL_VAR_DIR . '/tmp';
		            	System::rm(array('-rf', $tmpDir));
		            	$config = SGL_VAR_DIR . '/config';
		            	System::rm(array('-rf', $config));
		            }
		            if (defined('SGL_CACHE_DIR')) {
		                $cacheDir = SGL_CACHE_DIR . '/entities';
		                $tmplDir = SGL_CACHE_DIR . '/tmpl';
		                System::rm(array('-rf', $cacheDir));
		                System::rm(array('-rf', $tmplDir));
		            }
		            break;
		            
		        case 'blogweb' :
		        	if (defined('SGL_CACHE_DIR')) {
		        		$cacheDir = SGL_CACHE_DIR . '/templates_c';
		        		System::rm(array('-rf', $cacheDir));
		        	}
		            break;
		    }
		}
	}
}

class SGL_Task_rvsCreateFileSystem extends SGL_UpdateHtmlTask
{
	public function run($data=null)
	{
	    require_once 'System.php';

		foreach ($data['aModuleList'] as $module) {
		    switch (strtolower($module)) {
            case 'blogweb' :
                $cacheDir = SGL_CACHE_DIR . '/templates_c';
                if (!is_dir($cacheDir)) {
                    System::mkDir(array($cacheDir));
                    if (is_dir($cacheDir)) {
                        @chmod($cacheDir, 0777);
                    } else {
                        SGL_Install_Common::errorPush(SGL::raiseError('Problem creating template_c dir'));
                    }
                }
                break;
		    }
		}
	}
}

/**
 * validate new module to install:apiruk
 * call _cmd_install in SGL_MOD_DIR . '/default/classes/ModuleMgr.php';
 *
 */
class SGL_Task_rvsInstallNewModule extends SGL_UpdateHtmlTask
{
	public function run($data=null)
	{
	    require_once SGL_MOD_DIR . '/default/classes/ModuleMgr.php';
	    $oModule = new ModuleMgr();
	    $input = SGL_Registry::singleton();
	    $outputClass = SGL_FrontController::getOutputClass();
        $output = new $outputClass();
        ///fix PHP 5.3
        $output = &$output;
        
		foreach ($data['aModuleList'] as $module) {
		    $input->moduleName= strtolower($module);
		    if (!SGL::moduleIsEnabled($input->moduleName)) {
		        $oModule->_cmd_install($input, $output);        
		    }
		}
	}
}

class SGL_Task_rvsUpdateConfig extends SGL_UpdateHtmlTask
{
	public function run($data=null)
	{
	    //Start enable cache :Witoon
	    $c = SGL_Config::singleton();
	    $fileOptimizetion = SGL_VAR_DIR . '/rvoptimize.txt';
	    if (file_exists($fileOptimizetion) === false) {
	        $c->set('site', array('compression' => true));
	        $c->set('site', array('outputBuffering' => true));
	        $c->set('cache', array('enabled' => true));
	        $c->set('cache', array('libCacheEnabled' => true));
	        $c->set('cache', array('javascript' => true));	        
	        $handle = fopen($fileOptimizetion, 'w+');
	        fclose($handle);
	    }
	    //end enable cache : Witoon
		if (in_array('tryout', $data['aModuleList'])) {
			//tryout
			$c->set('tryoutlogin', array('subdomain_path' => $data['webRoot'] . '/tryout'));
			$c->set('tryoutlogin', array('rvsitebuilder_path' => (isset($data['rvsitebuilder_path'])) ?  $data['rvsitebuilder_path'] : 0));
			$c->set('tryoutlogin', array('main_ip' => (isset($data['main_ip'])) ? $data['main_ip'] : 0 ));
		}
		$configFile = SGL_VAR_DIR . '/' . SGL_SERVER_NAME . '.conf.php';
		$ok = $c->save($configFile);
		$a = $c->getAll();
	}
}

class RVS_Task extends SGL_UpdateHtmlTask
{
    var $groupId = null;
    var $childId = null;
	function rvsOverrideDefaultInstallSettings($data)
	{
		//RVS START auto setup
         if ( defined('RVS_AUTO_SETUP') && is_file(SGL_VAR_DIR . '/rvsautosetup.ini.php') ) {
            $aAutoConf = parse_ini_file(SGL_VAR_DIR . '/rvsautosetup.ini.php', true);
            $aAutoConf['aModuleList'] = (isset($aAutoConf['aModuleList'])) ? explode(',', $aAutoConf['aModuleList']) : $data['aModuleList'];
            $data['aModuleList'] = array_unique(array_merge((array)$data['aModuleList'], (array)$aAutoConf['aModuleList']));
            $data['siteCookie'] = $aAutoConf['siteCookie'];
            $data['adminPassword'] = $aAutoConf['adminPassword'];
            $data['adminPassword2'] = $aAutoConf['adminPassword2'];
            $data['adminUserName'] = $aAutoConf['adminUserName'];
            $data['adminEmail'] = $aAutoConf['adminEmail']; 
            
            //db
            $data['db']['charset'] = 'utf8';
            $data['db']['collation'] = 'utf8_unicode_ci';
            $data['db']['host'] = (isset($aAutoConf['Host']) && $aAutoConf['Host']) ? $aAutoConf['Host'] : 'localhost';
            $data['db']['protocol'] = (isset($aAutoConf['protocol']) && $aAutoConf['protocol']) ? $aAutoConf['protocol'] : 'unix';
            $data['db']['port'] = (isset($aAutoConf['Portname']) && $aAutoConf['Portname']) ? $aAutoConf['Portname'] : 3306;
            //log
            $data['log']['enabled'] = (isset($aAutoConf['logEnabled'])) ? $aAutoConf['logEnabled'] : 0;
            $data['log']['priority'] = (isset($aAutoConf['logPriority'])) ? $aAutoConf['logPriority'] : "PEAR_LOG_ERR";
            $data['log']['sizerotate'] = (isset($aAutoConf['logFileSizeRotate'])) ? $aAutoConf['logFileSizeRotate'] : 10; // 10M
            
            // lang
            $data['siteLanguage'] = $aAutoConf['siteLanguage'];
            
            $data['rvsitebuilder_path'] = (isset($aAutoConf['rvsitebuilder_path'])) ?  $aAutoConf['rvsitebuilder_path'] : 0;
            $data['main_ip'] = (isset($aAutoConf['main_ip'])) ?  $aAutoConf['main_ip'] : 0;
         }
        //RVS END
        return $data;
	}
	
	function rvsBuildDbCreateStatement($sql)
	{
	    if (preg_match('/create table/i', $sql)) {
	        $result = "";
	        //echo $statementType . "A: " . $sql . "<br>";
	        if (SGL_Config::get('db.charset')) {
	            $result .= ' CHARACTER SET ' . SGL_Config::get('db.charset');
	        }
	        if (SGL_Config::get('db.collation')) {
	            $result .= ' COLLATE ' . SGL_Config::get('db.collation');
	        }
	        $sql = preg_replace('/;\s*$/', $result . ';', $sql);
	        //echo "B: " . $sql . "<br><hr>"; exit;
	    }
	    return $sql;
	}
}

  class SGL_Task_rvsConvertCharsetDb extends SGL_UpdateHtmlTask
  {
  	var $charset = null;
  	var $dbh;
  	var $conf;
  	
  	public function run($data=null)
  	{
  		// if project charset is not utf-8 do not go to next step to convert
  		$projectCharset = RVSCOMPODB::getCurrentCharset();
  		if (strtolower($projectCharset) != 'utf-8') {
  			return true;
  		}
  		$c = SGL_Config::singleton();
  		$this->conf = $c->getAll();
  		$this->dbh = SGL_DB::singleton();
  		
  		$charset = (is_file(SGL_VAR_DIR . '/rvstemplateconf.ini.php'))
  					? parse_ini_file(SGL_VAR_DIR . '/rvstemplateconf.ini.php')
  					: array();
  		$aChar = array('cs'=> 'czech'
  		,'cy'=>'cymraeg'
  		,'da'=>'danish'
  		,'de'=>'deutsch'
  		,'en'=>'english'
  		,'es'=>'spanish'
  		,'eu'=>'basque'
  		,'fi'=>'finish'
  		,'fr'=>'french'
  		,'id'=>'indoneslan'
  		,'it'=>'italian'
  		,'ko'=>'korean'
  		,'lv'=>'latvian'
  		,'nb'=>'norwegian'
  		,'nl'=>'neterland'
  		,'pl'=>'polish'
  		,'pt'=>'portuguese'
  		,'br'=>'brazilian'
  		,'ro'=>'romanian'
  		,'ru'=>'russian'
  		,'sl'=>'slovenian'
  		,'sr'=>'serbian'
  		,'sv'=>'swedish'
  		,'uk'=>'ukrainian'
  		);
  		
  		//check charset
  		if (isset($charset['charset_name']) && in_array($charset['charset_name'], $aChar)) {
  			$aTable = array();
  			$aSQLOldData = array();
  			$aSQLToRestore = array();
  			// show all table
  			$query = "SHOW TABLES FROM {$this->conf['db']['name']}";
  			$allTable = $this->dbh->getAll($query);
  			foreach ($allTable as $k => $v) {
  				$key = array_keys(get_object_vars($v));
  				$table = (isset($key[0]) && isset($v->$key[0])) ? $v->$key[0] : null;
  				$aTable[] = $table;
  				//select table web_*
  				if (!is_null($table) && preg_match('/^' . $this->conf['db']['prefix'] . '/',$table)) {
  					// select data by table
  					$query = "SELECT * FROM {$table}";
  					//Fix PHP5.3 (use MDB2)
  					$resDataAll = $this->dbh->getAll($query, SGL_DB_FETCHMODE_ASSOC);
  					foreach ($resDataAll as $k => $v) {
  						//echo "<br>" .  $table;
  						$aSQLOldData[] = $this->buildSQLFormat($table, $resDataAll[$k]);
  						$tableName = preg_replace("/^[a-z0-9]+\_/i", "",$table);
  						$aSQLToRestore[] = $this->buildSQLFormat($tableName, $resDataAll[$k]);
  					}
  				}
  			}
			
  			// make file sql
  			if (count($aSQLOldData) && count($aSQLToRestore)) {
  				$this->writeSQLcommandTtoFile($aSQLOldData, $aSQLToRestore);
  			}
			// convert schema and collation 
			// ทำครั้งเดียว ถ้าต้องการ convert charset อีกครั้งให้ลบ table faqweb_convertutf8 แล้วรัน setup ใหม่
  			if ($this->getConvertUtf8() != 1 && count($aTable)) {
  				// create table before validate convert
                $this->createTableCheckConvert();
                
  				$this->convertCharsetAndCollate($aTable, $this->conf['db']['name']);
  				
  				// convert data in database
  				$this->convertCharsetDB();
  				
  				// insert data after convert complete
  				$this->insertTableCheckConvert();
  			}
  		}
  		//remove comment to debug 
  		//exit;
  	}

  		function getConvertUtf8() {
  		$sql = "SHOW TABLES LIKE '{$this->conf['db']['prefix']}faqweb_convertutf8'";
  		$res = $this->dbh->getOne($sql);
  		if ($res) {
  			return 1;
  		} else {
  			return 0;
  			}
  		}
  	/**
  	 * write SQL command to file
  	 * 1. file backUpDb.sql if have problem to setup.php you can restore database with this file
  	 * 2. file toUpdateDb.sql after convert schema and collation to UTF8 you can conver data with run this file 
  	 * with $result = SGL_Sql::parse($pathSql, 0, array('SGL_Sql', 'execute'));
  	 * $pathSql = SGL_VAR_DIR/toUpdateDb.sql
  	 *
  	 * @author pharadol & apiruk
  	 * @param unknown_type $aSQLOldData
  	 * @param unknown_type $aSQLToRestore
  	 */
  	function writeSQLcommandTtoFile($aSQLOldData, $aSQLToRestore)
  	{
  		SGL::logMessage('L: ' . __LINE__ , PEAR_LOG_DEBUG);
  		if (is_writable(SGL_VAR_DIR)) {
  			$str = "";
  			$toUpdateDb = SGL_VAR_DIR . '/toUpdateDb.sql';
  			$file = fopen($toUpdateDb, 'w+');
  			foreach ($aSQLToRestore as $data ) {
  				$str .= $data;
  			}
  			fwrite($file, $str);
  			fclose($file);

  			$str = "";
  			$backUpDb = SGL_VAR_DIR . '/backUpDb.sql';
  			$file = fopen($backUpDb, 'w+');
  			foreach ($aSQLOldData as $data ) {
  				$str .= $data;
  			}
  			fwrite($file, $str);
  			fclose($file);
  		}
  	}

  	/**
  	 * when convert schema and collation successful
  	 * next step to create table faqweb_convert to validate
  	 * @author pharadol & apiruk
  	 */
  	function createTableCheckConvert()
  	{
  		SGL::logMessage('L: ' . __LINE__ , PEAR_LOG_DEBUG);
  		$sql = sprintf("CREATE TABLE  IF NOT EXISTS %s (
                            id  INT( 1 ) NOT NULL ,
                            PRIMARY KEY ( id )
                            )
                            CHARACTER SET %s 
                            COLLATE %s;"
                            , $this->conf['db']['prefix'] . 'faqweb_convertutf8'
                            , SGL_Config::get('db.charset')
                            , SGL_Config::get('db.collation'));
                            $this->dbh->query($sql);             
  	}
  	
  	function insertTableCheckConvert()
  	{
  		$sql1 = "INSERT INTO {$this->conf['db']['prefix']}faqweb_convertutf8 (id) VALUES ('1')";
  		$res = $this->dbh->query($sql1);
  	}

  	/**
  	 * to do convert data to utf8 with project database charset
  	 * get database charset
  	 * $character_set_results = mysql_result(mysql_query("SELECT @@character_set_results"),0,0);
  	 * 
  	 * @author pharadol & apiruk
  	 * @return unknown
  	 */
  	function convertCharsetDB()
  	{
  		SGL::logMessage('L: ' . __LINE__ , PEAR_LOG_DEBUG);
  		require_once SGL_LIB_DIR . '/data/ary.languages.php';

  		// 1. select project db charset
  		$lang = SGL_Translation::getFallbackLangID(SGL_LANG_ID_SGL);
  		$xmlCharset = (isset($GLOBALS['_SGL']['LANGUAGE'][$lang][6])) ? $GLOBALS['_SGL']['LANGUAGE'][$lang][6] : null;
  		$projectDbCharset = (!is_null($xmlCharset)) ? preg_replace("/^[a-z0-9]+\-/i", "", $xmlCharset) : null;
  		//echo "<br>" . $projectDbCharset;

  		// 2. validate convert utf-8 exists
  		// if get lang name is fasle exit convert charset DB
  		$sql = "SELECT * FROM {$this->conf['db']['prefix']}faqweb_convertutf8";
  		$isConvertUtf8Exist = $this->dbh->getOne($sql);

  		// validate to do convert database 1 ครั้งเท่านั้น
  		if (is_null($projectDbCharset) || (!SGL::isError($isConvertUtf8Exist) && $isConvertUtf8Exist)) {
  			SGL::logMessage('Cannot get project charset', PEAR_LOG_DEBUG);
  			return false;
  		}

  		// 3. SET NAME to project database charset
  		mysql_query("SET NAMES {$projectDbCharset}");

  		// 4. update data
  		//require_once SGL_LIB_DIR . '/SGL/Sql.php';
  		//require_once SGL_LIB_PEAR_DIR . '/DB.php';
  		$pathSql = SGL_VAR_DIR .'/toUpdateDb.sql';
  		$result = SGL_Sql::parse($pathSql, 0, array('SGL_Sql', 'execute'));
  		if (SGL_DB_DRIVER == 'DB') {
			$errorCode = DB_ERROR_ALREADY_EXISTS;
  		} else {
			$errorCode = MDB2_ERROR_ALREADY_EXISTS;
  		}
  		if (SGL::isError($result, $errorCode)) {
  			print_r($result);
  			SGL::logMessage("****RUN SQL COMMANDE ERROR ***** Please check " . $pathSql , PEAR_LOG_ERR);
  			return false;
  		}

  		// 5. SET NAME to utf8
  		mysql_query("SET NAMES utf8");
  		return $result = isset($result) ? true : false;
  	}
  	
  	function setArrayKeyToLowerCase($result)
  	{
  		$aBuff = array();
  		foreach ($result[0] as $key => $val) {
  			//SGL::logMessage('$key-before: ' . $key . __LINE__ , PEAR_LOG_DEBUG);
  			$key = strtolower($key);
  			//SGL::logMessage('$key-after: ' . $key . __LINE__ , PEAR_LOG_DEBUG);
  			$aBuff[$key] = $val;
  		}
  		$result[0] = $aBuff;
  		return $result;
  	}

    /**
     * loop change schema table and colums to utf8
     *
     * @param unknown_type $aTable
     * @param unknown_type $dbName
     */
    public static function convertCharsetAndCollate($conn, $dbName)
    {
    	SGL::logMessage('L: ' . __LINE__ , PEAR_LOG_DEBUG);
        $tabs = array();
		$tabs = $aTable;
        // loop table name
        foreach ($tabs as $tab) {
            //DROP INDEX
        	if (preg_match('/(.*?)_seq/i', $tab)) {
        		//SGL::logMessage('*******table: ' . $tab . __LINE__ , PEAR_LOG_DEBUG);
        		continue;
        	}
        	//Fix PHP5.3 (use MDB2)
        	$res = $this->dbh->getAll("show index from {$tab}", SGL_DB_FETCHMODE_ASSOC);
        	if (count($res[0]) <= 0) {
        		continue;
        	}
        	//Fix PHP5.3 (use MDB2) //เปลี่ยนมาใช้  MDB2 แล้ว key กลายเป็นตัวเล็ก
        	$res = $this->setArrayKeyToLowerCase($res);
        	/*
            $key_name = isset($res[0]['Key_name']) 
                ? $res[0]['Key_name'] 
                : isset($res[0]['key_name']) 
                    ? $res[0]['key_name']
                    : '';
            
            $unique = isset($res[0]['Non_unique']) 
                ? $res[0]['Non_unique'] 
                : isset($res[0]['non_unique']) 
                    ? $res[0]['non_unique']
                    : '';
                    */
        	//TODO: isError
            $indicies = array();
        	if ($res[0]['key_name'] != "PRIMARY") {
            	$indicies[] = array("name" => $res[0]['key_name'], "unique" => !($res[0]['non_unique'] == "1"), "col" => $res[0]['column_name']);
            	$res3 = $this->dbh->query("ALTER TABLE {$tab} DROP INDEX {$res[0]['key_name']}");
            	//TODO: isError
            	//echo "Dropped index {$row[2]}. Unique: {$row[1]}\n";
            }
            
            // convert table and all field to utf8
            $command = "ALTER TABLE {$tab} CONVERT TO  CHARACTER SET utf8 COLLATE utf8_general_ci";
            $res5 = $this->dbh->query($command);
                
            // re-build indicies..
            foreach ($indicies as $index) {
                if ($index["unique"]) {
                    $res6 = $this->dbh->query("CREATE UNIQUE INDEX {$index["name"]} ON {$tab} ({$index["col"]})");
                    //TODO: isError
                } else {
                    $res7 = $this->dbh->query("CREATE INDEX {$index["name"]} ON {$tab} ({$index["col"]})");
                    //TODO: isError
                    //echo "CREATE INDEX {$index["name"]} ON {$tab}. Unique: {$index["unique"]}\n";
                }
            }
            // set table default collate
            $res8 = $this->dbh->query("ALTER TABLE {$tab}  DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
            //TODO: isError
        }
        // set database charset
        //ALTER DATABASE `databasename` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
        $res9 = $this->dbh->query("ALTER DATABASE `{$dbName}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
        //TODO: isError
    }
    
  	//sql replace into
  	function buildSQLFormat($table, $aData = array())
  	{
  		$field ='';
  		$value = '';
  		foreach ($aData as $k => $v) {
  			$field .= sprintf('%s', ($field != '') ? ', ' : '');
  			$field .= $k;
  			$value .= sprintf('%s', ($value != '') ? ', ' : '');
  			$value .= sprintf('%s', (is_null($v)) ?  'null' : $this->quoteSmart($v));
  		}

  		$line = sprintf('REPLACE INTO %s (%s) VALUES (%s);', $table, $field, $value);
  		$line .= "\n";
  		return $line;
  	}

  	function quoteSmart($value)
  	{
  		$value = "'" . mysql_real_escape_string($value) . "'";
  		return $value;
  	}
  	
  }
  
  class SGL_Task_rvsConvertFileToUtf8 extends SGL_UpdateHtmlTask
  {
  	public function run($data=null)
  	{
  		require_once SGL_LIB_DIR . '/SGL/RVConvertFIleUtf8.php';
  		$oRVConvert = new RVConvertFileUtf8();
  		// if project charset is not utf-8 do not go to next step to convert
  		$projectCharset = RVSCOMPODB::getCurrentCharset();
  		if (strtolower($projectCharset) != 'utf-8') {
  			return true;
  		}
  		$c = SGL_Config::singleton();
  		$this->conf = $c->getAll();
  		$lang = SGL_Translation::getFallbackLangID(SGL_LANG_ID_SGL);
  		$xmlCharset = (isset($GLOBALS['_SGL']['LANGUAGE'][$lang][5])) ? $GLOBALS['_SGL']['LANGUAGE'][$lang][5] : null;
  		$projectDbCharset = (!is_null($xmlCharset)) ? preg_replace("/^[a-z0-9]+\-/i", "", $xmlCharset) : null;
  		$ignoreDirForHomePath = array("rvsUtf8Backup", "RvSitebuilderPreview");
  		$charsetValue = (isset($projectDbCharset)) ? $projectDbCharset : 'iso-8859-15';
  		
  		$aModule = $this->getModuleList();
  		foreach ($aModule as $moduleName) {
  			switch (strtolower($moduleName)) {
        	case 'faqweb':
        		$pathUser = $this->conf['path']['webRoot'] . '/faqweb/images/Image';
        		//convert file to utf8
        		if (is_dir($pathUser)) {
        		    $oRVConvert->convertCharsetFile($charsetValue, $pathUser, $toFilePattern = '', $ignoreDirForHomePath);
        		}
        		break;
        	case 'blogweb':
        		break;
        	case 'forums':
        		break;
  			}
  		}
  		
  	}
  	
  	function getModuleList()
  	{
  		$data['aModuleList'] = array();
  		$data['aModuleList'] = SGL_Install_Common::getModuleList();
  		if (count($data['aModuleList'])) {
  			foreach ($data['aModuleList'] as $key => $moduleName) {
  				if (!SGL::moduleIsEnabled($moduleName)) {
  					unset($data['aModuleList'][$key]);
  				}
  			}
  		}
  		return $data['aModuleList'];
  	}

  }
  
  class SGL_Task_rvsUpdatePreferencesUser extends SGL_UpdateHtmlTask
  {
      var $dbh = null;
      var $conf = array();
      public function run($data=null)
      {
           require_once SGL_MOD_DIR . '/user/classes/PreferenceMgr.php';
           $input = SGL_Registry::singleton();
           $outputClass = SGL_FrontController::getOutputClass();
           $output = new $outputClass();
             ///fix PHP 5.3
           $output = &$output;
           $aPreference = $this->getUserPreference();
           if (count($aPreference)) {
               $oPreferrence = new PreferenceMgr();
               $input->aDelete = $aPreference;               
               $oPreferrence->_cmd_updatePreferencesForAllMembers($input, $output);
           }           
      }
      
      function getUserPreference()
      {
          $aData = array();
          $c = SGL_Config::singleton();
          $this->conf = $c->getAll();
  		  $this->dbh = SGL_DB::singleton();
  		  $query = sprintf("SELECT preference_id FROM %s WHERE name = 'locale'", SGL_Config::get('table.preference'));
  		  $res = $this->dbh->getAll($query);
  		  foreach ($res as $k => $obj) {
  		      $aData[$k] = $obj->preference_id;
  		  }
  		  return $aData;
  		  
      }
      
  }
  
  
  class  SGL_Task_rvsUninstallModule extends SGL_UpdateHtmlTask
  {
  	var $dbh = null;
  	var $conf = array();
  	public function run($data=null)
  	{
  		require_once SGL_MOD_DIR . '/default/classes/ModuleMgr.php';
        $input = SGL_Registry::singleton();
        $outputClass = SGL_FrontController::getOutputClass();
        $output = new $outputClass();
        $output = &$output;
  		$aModuleList = SGL::getmodullistDB();
  		foreach ($aModuleList as $key => $aModuleName) {
  			if(!in_array($aModuleName , $data['aModuleList'])) {
  				$oModule = new ModuleMgr();
                $input->moduleId = $key;
                $oModule->_cmd_uninstall($input, $output);
  				
  			}
  		}

  	}
  }
  
   class  SGL_Task_rvsInstallModule extends SGL_UpdateHtmlTask
  {
    var $dbh = null;
    var $conf = array();
    public function run($data=null)
    {
    	require_once SGL_MOD_DIR . '/default/classes/ModuleMgr.php';
    	$input = SGL_Registry::singleton();
    	$outputClass = SGL_FrontController::getOutputClass();
        $output = new $outputClass();
        $output = &$output;
        $aModuleList = SGL::getmodullistDB();

        foreach ($data['aModuleList'] as $k => $moduleName) {
        	
            if(!in_array($moduleName , $aModuleList)) {
            	$oModule = new ModuleMgr();
            	$input->moduleName = $moduleName;
            	$oModule->_cmd_install($input, $output);
            }
        }

    }
  }

?>