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-php56/root/usr/share/pear/RVSeagullMod/modules/forums/classes/AdminForumsMgr.php
<?php
##copyright##
require_once 'Validate.php';
require_once 'DB/DataObject.php';
/**
 * 
 *
 * @package forums
 * @author  
 * @version 
 * @since   PHP 4.1
 */
class AdminForumsMgr extends SGL_Manager 
{
	function AdminForumsMgr()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        parent::SGL_Manager();
        
        $this->pageTitle        = 'Admin ForumsMgr';
        $this->template         = 'forums.html';
        
        $this->_aActionsMapping =  array(
            'list'   => array('list')      // Compose newsletter            
            ,'integrate' => array('integrate')
            ,'agreement' => array('agreement')
            ,'updatedatabase' => array('updatedatabase')
        );
    }


    function validate($req, &$input)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $this->validated    = true;
        $input->error       = array();
        $input->pageTitle   = $this->pageTitle;
        $input->masterTemplate = 'masterLeftCol.html';
        $input->template    = $this->template;
        $input->action      = ($req->get('action')) ? $req->get('action') : 'list';
        $input->moduleName  = $req->get('moduleName');
        //detect phpsu
        $input->isPhpsuExec 	= (preg_match("/cgi|apache2filter/i", php_sapi_name())) ? true : false;
        $input->langDefaultPath	= SGL_Config::get('path.webRoot') . '/forums/Themes/default/languages';
		$lang			=	$_SESSION['aPrefs']['language'];
       	$aLangName		=	$GLOBALS['_SGL']['LANGUAGE'][strtolower($lang)];
        $input->langId		= strtolower($aLangName[2]);
        $langName = (isset($aLangName[4])) ? $aLangName[4] : $lang;  
        $input->langName = ($input->langId == 'en') ? 'english' : $this->getLangNameForums($input->langId);
        $input->isForumsSupportLang = $this->isForumsSupportLang($input->langId);
        
		$input->langRvtheme		= SGL_Config::get('path.webRoot') . '/forums/Themes/default/languages';
		$input->bu_setup =  $req->get('bu_setup');
		$input->frmagree = $req->get('frmagree');
		$input->frmPassword = $req->get('frmPassword');

		//validate agreement
		if ($input->bu_setup == 'Setup') {
		    if ($input->frmagree == 'yes' && $input->frmPassword !=''){
		        $ok = $this->_isOriginalPassword($input->frmPassword);
		        if ($ok == false) {
		             $aErrors['passwordincorerct'] = SGL_Output::translate('Admin password is incorrect');
		        } else {
		        	$input->action = 'integrate';
		        }
		    } elseif ($input->frmagree == 'yes' && $input->frmPassword == ''){
		      $aErrors['nopassword'] = SGL_Output::translate('you must entered your original password');
		     } elseif ($input->frmagree == 'no'){
		       $aErrors['donotaccept'] = SGL_Output::translate('you must select Accept before setup');
		    } 
		}

     // validate check integrate success
	    $FileInstall = $this->checkFileInstallComplete();
	    if($FileInstall) {
	         $input->template = 'forumsComplete.html';
	    } else {
	         $input->template = 'forums.html';
	    }
	    
	    switch ($input->action) {
	        case 'agreement':
	            $input->getLicense = $this->getLicenseSMF();
	            $input->template="forums_agreement.html";
	            break;
	        case 'integrate':
	            $input->template = 'forumsComplete.html';
	            break;
	    }
	    
       
        if (isset($aErrors) && count($aErrors)) {
            $input->error = $aErrors;
            $input->action = 'agreement';
            $this->validated = false;
        }
    }
	

    /**
    * Display the compose form
    *
    * @access public
    *
    */
    function _cmd_list($input, &$output)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);   
        //1. validate download SMF forums and copy to {path} if not success show button  [verify]
        $path = $this->validate_path();
        $output->aMesPh =($path == false)? true : false;
        //2. validate permission file / folder SMF if not success show button [verify]
        $aNoChmodP = $this->validate_checkPermission($input);
        if(count($aNoChmodP)>0) {
            $output->aMes = $aNoChmodP;
        }
        //3. validate download integration patch from web RVSitebuilder (rvthems) if not success show button [verify]
        $pathRvtheme = $this->validate_integrationPath($input);
        if(count($pathRvtheme) > 0) {
            $output->aMesTheme = $pathRvtheme;
        }
       //$output->aMesTheme =($pathRvtheme == false)? true : false;
        //4. validate button [Install]
        $output->aNoMes = (count($aNoChmodP) == 0 && $path == true && (count($pathRvtheme) == 0)) ? true : false;
        //show menu
        // Forums Admin
        //    + Update Integration Path
        //    + Manage forums link go to smf admin

        //recommend
        //1. download file lang
        // copy lang to {path}
        if ($this->isLang($input->langDefaultPath,$input->langId,$input->langRvtheme, $input->langName) == 0) {
        	$output->isIncorrectLangFile1 = true;
        	$lang			=	$_SESSION['aPrefs']['language'];
        	$aLangName		=	$GLOBALS['_SGL']['LANGUAGE'][$lang];
        	$aLangName 		= 	explode ( "-" , $aLangName[1] );
        	$output->LangIncorrect = $aLangName[0];
        }     
          
    }
    
    function _cmd_updatedatabase($input)
    {
    	SGL::logMessage(null,PEAR_LOG_DEBUG);
    	$ok =  $this->runSQLFile();
    	if ($ok) {
            SGL::raiseMsg('Update database forums successfully', true, SGL_MESSAGE_INFO);
        }		
    }
    
    /**
     * validate forums folder download success
     *
     * @param unknown_type $input
     * @return unknown
     */
    function validate_path()
    {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aPath =  $this->getPathwww();
        foreach($aPath as $key => $value){
            if(!file_exists($value)) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * call smf_api.php
     * for register account admin if don't have in table forums_members
     *
     * @param unknown_type $input
     * @param unknown_type $output
     * @return boolean true/false
     */
    function verifyAdmin(&$input, &$output)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);    	
    	require_once SGL_Config::get('path.webRoot')  . '/forums/Api.php';    	
    	$oForumsApi = new ForumsApi();
    	$ok = $oForumsApi->verifyAccount();
        $okLogin = $oForumsApi->login($input->frmPassword);
        if (!$ok) {
        	SGL::logMessage('Verify admin account fail', PEAR_LOG_ERR);
            SGL::raiseMsg('Verify admin account fail');
            return false;
        }
        if (!$okLogin) {
        	SGL::logMessage('Login admin account fail', PEAR_LOG_ERR);
            SGL::raiseMsg('Login admin account fail');
            return false;
        }
     	SGL::logMessage('verify admin is ok', PEAR_LOG_DEBUG);   
        return true;
    }
    
    function getPathwww()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aPath = array();
        //requirement
        $forumsPath = SGL_Config::get('path.webRoot') . '/forums';
        $aPath['pathASttachments'] = $forumsPath . '/attachments';
        $aPath['pathAvatars'] = $forumsPath . '/avatars';
        $aPath['pathThemes'] = $forumsPath . '/Themes';
        $aPath['pathPackages'] = $forumsPath . '/Packages';
        $aPath['pathSmileys'] = $forumsPath . '/Smileys';
        $aPath['pathSources'] = $forumsPath . '/Sources';
        $aPath['fileIndex'] = $forumsPath . '/index.php';
        $aPath['fileInstall1_1Sql'] = $forumsPath . '/install_2-0_mysql.sql';
        $aPath['fileInstall'] = $forumsPath . '/install.php';
        $aPath['fileLicenseTxt'] = $forumsPath . '/license.txt';
        $aPath['fileNewsReadmeHtml'] = $forumsPath . '/news_readme.html';
        $aPath['fileReadmeHtml'] = $forumsPath . '/readme.html';
        $aPath['fileSettingsBakPhp'] = $forumsPath . '/Settings_bak.php';
        $aPath['fileSettingsPhp'] = $forumsPath . '/Settings.php';
        $aPath['filessiExamplesPhp'] = $forumsPath . '/ssi_examples.php';
        $aPath['fileSsiExamplesShtml'] = $forumsPath . '/ssi_examples.shtml';
        $aPath['fileSSIPhp'] = $forumsPath . '/SSI.php';
        $aPath['fileagreementTxt'] = $forumsPath . '/agreement.txt';
        
        
            
      return $aPath;
    }
    
    /**
     * validate permission file and folder
     * phpsu => 755
     * dso => 777
     *
     * @return unknown
     */
    function validate_checkPermission()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aPath = $this->getPathwww();
        $aNoChmodP = array();
        $pathforums = SGL_Config::get('path.webRoot') . '/forums';
        $pathIndex = SGL_Config::get('path.webRoot') . '/forums/index.php';
        $pathSSI =  SGL_Config::get('path.webRoot') . '/forums/SSI.php';
        $pathInstallList =  $aPath['pathPackages'] . '/installed.list';
        $pathLoad = SGL_Config::get('path.webRoot') . '/forums/Sources/Load.php'; 
        $pathSubMember = SGL_Config::get('path.webRoot') . '/forums/Sources/Subs-Members.php'; 
        $pathtableAliases = SGL_Config::get('path.webRoot') . '/forums/tableAliases.ini';
        
        if (!is_writable($pathSubMember)) {
            $aNoChmodP['pathSubMember'] = $pathSubMember;
        }
        if (!is_writable($pathLoad)) {
            $aNoChmodP['pathLoad'] = $pathLoad;
        }
        if (!is_writable($pathforums)) {
            $aNoChmodP['pathforums'] = $pathforums;
        }
        if (!is_writable($aPath['pathASttachments'])) {
            $aNoChmodP['pathASttachments'] = $aPath['pathASttachments'];
        }
        if (!is_writable($aPath['pathAvatars'])) {
            $aNoChmodP['pathAvatars'] = $aPath['pathAvatars'];
        }
        if (!is_writable($aPath['pathPackages'])) {
            $aNoChmodP['pathPackages'] = $aPath['pathPackages'];
        }
        if (!is_writable($pathInstallList)) {
            $aNoChmodP['pathPackages'] = $pathInstallList;
        }
        if (!is_writable($aPath['pathSmileys'])) {
            $aNoChmodP['pathSmileys'] = $aPath['pathSmileys'];
        }
        if (!is_writable($aPath['pathThemes'])) {
            $aNoChmodP['pathThemes'] = $aPath['pathThemes'];
        }
        if (!is_writable($aPath['fileagreementTxt'])) {
            $aNoChmodP['fileagreementTxt'] = $aPath['fileagreementTxt'];
        }
        if (!is_writable($aPath['fileSettingsPhp'])) {
            $aNoChmodP['fileSettingsPhp'] = $aPath['fileSettingsPhp'];
        }
        if (!is_writable($aPath['fileInstall'])) {
            $aNoChmodP['fileInstall'] = $aPath['fileInstall'];
        }
        if(!is_writable($aPath['fileSettingsBakPhp'])) {
            $aNoChmodP['fileSettingsBakPhp'] = $aPath['fileSettingsBakPhp'];
        }
        if(!is_writable($pathtableAliases)) {
            $aNoChmodP['tableAliasesIni'] = $pathtableAliases;
        }
        if(!is_writable($pathIndex)) {
            $aNoChmodP['FileIndex'] = $pathIndex;
        }
        if(!is_writable($pathSSI)) {
            $aNoChmodP['FileSSI'] = $pathSSI;
        }

        return $aNoChmodP;
    }

    /**
     * validate rvtheme folder exists
     *
     * @return unknown
     */
    function validate_integrationPath()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aPath =  $this->getPathwww();
        $aPathFile = array();
        $pathRvtheme = $aPath['pathThemes'] . '/rvtheme';
        $pathFilesvSettings = SGL_Config::get('path.webRoot') . '/forums/rvSettings.php';
        $pathFilesmfApi = SGL_Config::get('path.webRoot') . '/forums/smf_api.php';
 
        if(!is_dir($pathRvtheme)) {
            $aPathFile['rvtheme'] = $pathRvtheme;
        }
        if(!is_file($pathFilesvSettings)) {
            $aPathFile['rvSettings'] = $pathFilesvSettings;
        }
        if(!is_file($pathFilesmfApi)) {
            $aPathFile['smfapi'] = $pathFilesmfApi;
        }
        return $aPathFile;
    }
    
    function _cmd_agreement($input, &$output)
    {
			$output->getLicense = $this->getLicenseSMF();
    }   
    
    function _cmd_integrate($input, &$output)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $pathSittings = SGL_Config::get('path.webRoot') . '/forums/Settings.php';
        $pathSSI = SGL_Config::get('path.webRoot') . '/forums/SSI.php';
        $pathIndex = SGL_Config::get('path.webRoot') . '/forums/index.php';
        $pathLoad = SGL_Config::get('path.webRoot') . '/forums/Sources/Load.php'; 
        $pathSubMember = SGL_Config::get('path.webRoot') . '/forums/Sources/Subs-Members.php'; 
        $pathInstall = SGL_Config::get('path.webRoot') . '/forums/install.php'; 
        $pathAchmentsIndex = SGL_Config::get('path.webRoot') . '/forums/attachments/index.php';
        $pathAvatarsIndex= SGL_Config::get('path.webRoot') . '/forums/avatars/index.php';
        $pathCache = SGL_Config::get('path.webRoot') . '/forums/cache/index.php';
        $pathPackagesIndex = SGL_Config::get('path.webRoot') . '/forums/Packages/index.php';
        $pathSmileysIndex = SGL_Config::get('path.webRoot') . '/forums/Smileys/index.php';
        $pathSourcesIndex = SGL_Config::get('path.webRoot') . '/forums/Sources/index.php';
        $pathThemesIndex = SGL_Config::get('path.webRoot') . '/forums/Themes/index.php';

        //update file Sitting
        $this->updateFileSettings($pathSittings);
        //update file index.php , file SSI.php
        $aDataReplace = $this->getPatternAndReplaceToFileIndexAndFileSsi();
        $this->updateFileIndexAndFileSsi($aDataReplace['PattenFileIndex'],  $aDataReplace['ReplaceFileIndex'], $pathIndex);
        $this->updateFileIndexAndFileSsi($aDataReplace['PattenFileSsi'],  $aDataReplace['ReplaceFileSsi'], $pathSSI);
        //end update file index.php , file SSI.php
        if (is_file($pathLoad)) {
        $aData = $this->getaPattanAndaReplaceFileLoad();
        $this->updateFileIndexAndFileSsi($aData['aPattan'],  $aData['aReplace'], $pathLoad);
        }
        
        if(is_file($pathSubMember)) {
            $aDataFileSubsMembers = $this->getaPattanAndaReplaceFileSubsMembers();
            $this->updateFileIndexAndFileSsi($aDataFileSubsMembers['aPattan'],  $aDataFileSubsMembers['aReplace'], $pathSubMember);
        }
        
        //replace file instail
        if(is_file($pathInstall)) {
            $aDataFileInstall = $this->getaPattanAndaReplaceFileinstall();
            $this->updateFileIndexAndFileSsi($aDataFileInstall['aPattan'],  $aDataFileInstall['aReplace'], $pathInstall);
        }
        
       //replace file Achments/Index
        if(is_file($pathAchmentsIndex)) {
            $aDataFileAchmentsIndex = $this->getaPattanAndaReplaceFileIndexAttachment();
            $this->updateFileIndexAndFileSsi($aDataFileAchmentsIndex['aPattan'],  $aDataFileAchmentsIndex['aReplace'], $pathAchmentsIndex);
        }
        
      //replace file Avatars/Index
        if(is_file($pathAvatarsIndex)) {
            $aDataFileAvatarsIndex = $this->getaPattanAndaReplaceFileIndexAttachment();
            $this->updateFileIndexAndFileSsi($aDataFileAvatarsIndex['aPattan'],  $aDataFileAvatarsIndex['aReplace'], $pathAvatarsIndex);
        }

      //replace file cache/index.php
        if(is_file($pathCache)) {
            $aDataFileCache = $this->getaPattanAndaReplaceFileIndexAttachment();
            $this->updateFileIndexAndFileSsi($aDataFileCache['aPattan'],  $aDataFileCache['aReplace'], $pathCache);
        }

     //replace file Packages/index.php
        if(is_file($pathPackagesIndex)) {
            $aDataFilePackagesIndex = $this->getaPattanAndaReplaceFileIndexAttachment();
            $this->updateFileIndexAndFileSsi($aDataFilePackagesIndex['aPattan'],  $aDataFilePackagesIndex['aReplace'], $pathPackagesIndex);
        }
        
       //replace file Smileys/index.php
        if(is_file($pathSmileysIndex)) {
            $aDataFileSmileysIndex = $this->getaPattanAndaReplaceFileIndexAttachment();
            $this->updateFileIndexAndFileSsi($aDataFileSmileysIndex['aPattan'],  $aDataFileSmileysIndex['aReplace'], $pathSmileysIndex);
        }
        
       //replace file Sources/index.php
        if(is_file($pathSourcesIndex)) {
            $aDataFileSourcesIndex = $this->getaPattanAndaReplaceFileIndexAttachment();
            $this->updateFileIndexAndFileSsi($aDataFileSourcesIndex['aPattan'],  $aDataFileSourcesIndex['aReplace'], $pathSourcesIndex);
        }
        
        //replace file Themes/index.php
        if(is_file($pathThemesIndex)) {
            $aDataFileThemesIndex = $this->getaPattanAndaReplaceFileIndexAttachment();
            $this->updateFileIndexAndFileSsi($aDataFileThemesIndex['aPattan'],  $aDataFileThemesIndex['aReplace'], $pathThemesIndex);
        }
        
        
        
        
        
        // update file install_1_1.sql
        $aData = $this->getPatternAndReplaceToFileSql();
        $res = $this->updateFileSqlInstall($aData['pattern'], $aData['replace'], $aData['string']);
		
        // end update file install_1_1.sql
        if ($res) {
            $ok = $this->runSQLFile();
        }
        
        if ($ok) {
        	//== Add Table Forums To File Config ===
        	if (!$this->addTableForumsToFileConfig()) {
        		SGL::raiseMsg('Error update config file unsuccessfuly');
        	}
            if($this->isTableForumsMembersExist()){
                $this->verifyAdmin($input, $output);
            }
            $this->deleteFileInstall();
            SGL::raiseMsg('Integrate database forums successfully', true, SGL_MESSAGE_INFO);  
        } else {
           SGL::raiseMsg('Integrate database fail');
        }
        
    }
    

    
	function getLicenseSMF()
	{	
	    SGL::logMessage(null,PEAR_LOG_DEBUG);
    	$filelicense =SGL_Config::get('path.webRoot') . '/forums/license.txt';
    	$aLine = file($filelicense);
    	
    	foreach ($aLine as $line) {
             $licensetxt.= $line;
    	}
        return $licensetxt;
	}
	
    function isTableForumsMembersExist()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);   
        $query = sprintf("
                         SHOW TABLES LIKE 
                       		  '%s'
							"
                         , $this->conf['db']['prefix'] . 'forums_members'
                         );
              $res =  $this->dbh->getOne($query);              
              if ($res) {
                  return true;
              } else {
                  return false;
              }
    }
    
    function isIntegrateComplete() 
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);   
        // the last table
       $query = sprintf("
                         SHOW TABLES LIKE 
                       		  '%s'
							"
                         , $this->conf['db']['prefix'] . 'forums_topics'
                         );
        // the last data
        $query1 = sprintf("
                         SHOW TABLES LIKE
                       		  '%s'
							"
                         , $this->conf['db']['prefix'] . 'forums_settings'
                         );
                         
      $query2 = sprintf("
                           SELECT 
                                    *
                           FROM 
                                      %s
                           WHERE
                           			variable = 'theme_default'
                           			AND value = '17'
                                       "
                       , $this->conf['db']['prefix'] . 'forums_settings'
                          );

        $resTableTopics =   $this->dbh->getOne($query);
        $resTableSettings =   $this->dbh->getOne($query);
        if ($resTableTopics && $resTableSettings) {
            $resValueRvtheme =   $this->dbh->getAll($query2);
        }
        
        if (isset($resValueRvtheme) && $resValueRvtheme) {
            return true;
        } else {
            return false;    
        }
    }
    
    function  runSQLFile()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        //echo SGL_CORE_DIR . '/Sql.php';
        require_once SGL_LIB_DIR . '/SGL/Sql.php';
        require_once SGL_LIB_PEAR_DIR . '/DB.php';
        require_once SGL_LIB_DIR . '/SGL/Task/Install.php';
        require_once SGL_LIB_DIR . '/SGL/Task/rvsUpdateDatabase.php';

       $pathInstallComplete = SGL_Config::get('path.webRoot') . '/forums/installcomplete.sql';

        if (file_exists($pathInstallComplete)) {
            $result = SGL_Sql::parse($pathInstallComplete, 0, array('SGL_Sql', 'execute'));
            if (PEAR::isError($result)) {
                SGL::logMessage("SQL fail......", PEAR_LOG_ERR);
                return false;
            }
               return true;
        }
        return false;
    }
    
    /**
     * Enter description here...
     *
     * @return unknown
     */
    function getPatternAndReplaceToFileSql()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        include_once  SGL_Config::get('path.webRoot') . '/forums/Themes/default/languages/Install.english.php';

        $boarddir = SGL_Config::get('path.webRoot') . '/forums';
        //TODO ตัด ให้เหลือ /ForumNewVersion/forums
        $boardurl = '/'. basename(SGL_Config::get('path.webRoot')) . '/forums';     //'/' . basename(RVSGLWrapper::getSGLBaseURL(0)) . '/forums';
        $path = SGL_Config::get('path.webRoot') . '/forums/install_2-0_mysql.sql';
        $aSqlVal = file($path);
        $string = implode('<RVS>\n</RVS>', $aSqlVal);
        preg_match_all('/\{\s*\$(.*?)\}/', $string, $matches);
        $aPattern = array_unique($matches[0]);
        $aReplace = array();
        foreach ($aPattern as $k => $v) {
            if (preg_match('/^\{\$default\_/',$v)) {
                $key = preg_replace('/^\{\$|\}$/', '', trim($v));
                $aReplace[$k] = (isset($txt[$key])) ? mysql_real_escape_string($txt[$key]) : '';
            } else {
                $key = preg_replace('/^\{\$|\}$/', '', trim($v));
                
                //SMF version
                if ($key == 'smf_version') {
                    $aReplace[$k] = (isset($GLOBALS['modSettings']['smfVersion'])) ? $GLOBALS['modSettings']['smfVersion'] : '2.0'; 
                } elseif ($key == 'db_prefix') {
                    $aReplace[$k] = 'forums_'; //not work //(isset($db_prefix)) ? $db_prefix : $GLOBALS[$key]; 
                } elseif (isset($GLOBALS['modSettings'][$key])) {
                    $aReplace[$k] = (isset($GLOBALS['modSettings'][$key])) ? $GLOBALS['modSettings'][$key] : '';
                } elseif (isset($GLOBALS[$key])) {
                    $aReplace[$k] = (isset($GLOBALS[$key])) ? $GLOBALS[$key] : '';
                } elseif ($key == 'boarddir' && isset($boarddir)) {
                   $aReplace[$k] = $boarddir;
                } elseif ($key == 'boardurl' && isset($boardurl)) {
                    $aReplace[$k] = $boardurl;
                } elseif ($key == 'enableCompressedOutput') {
                    $aReplace[$k] = 0;
                } elseif ($key == 'databaseSession_enable') {
                    $aReplace[$k] = 1;
                } elseif ($key == 'sched_task_offset') {
                    $aReplace[$k] = 111666;
                }
            }           
        } // end forech
        
        /*
        echo  $boarddir;
        echo "<pre>Pattern: total " . count($aPattern);
        echo "<br>Replace: total " . count($aReplace);
        print_r(array_diff_key($aPattern, $aReplace));
        print_r($aPattern);
        print_r($aReplace);
 		*/
        ///Replace config guest_hideContacts (default enable) :: Witoon
        $string = preg_replace('/\(\'guest_hideContacts\'(.*?)\'0\'\)/', '(\'guest_hideContacts\', \'1\')', $string);
        ///Replace config enableErrorLogging (default disable)
        $string = preg_replace('/\(\'enableErrorLogging\'(.*?)\'1\'\)/', '(\'enableErrorLogging\', \'0\')', $string);
        
        $aData['string'] = $string;
        $aData['pattern'] = $aPattern;
        $aData['replace'] = $aReplace;
        return $aData;
        
     /*   $aReplace = array($GLOBALS['db_prefix'] //$GLOBALS
                                , $txt['default_board_name']
                                , $txt['default_board_description']
                                , $txt['default_category_name']
                                , $txt['default_administrator_group']
                                , $txt['default_global_moderator_group']
                                , $txt['default_moderator_group']
                                , $txt['default_newbie_group']
                                , $txt['default_junior_group']
                                , $txt['default_full_group']
                                , $txt['default_senior_group']
                                , $txt['default_hero_group']
                                , $txt['default_topic_subject']
                                , $txt['default_topic_message']
                                , $GLOBALS['current_smf_version'] //$GLOBALS
                                , $txt['default_news']
                                , $GLOBALS['modSettings']['enableCompressedOutput'] //$GLOBALS
                                , $txt['default_karmaLabel']
                                , $txt['default_karmaSmiteLabel']
                                , $txt['default_karmaApplaudLabel']
                                , $GLOBALS['boarddir'] //$GLOBALS
                                , $txt['default_reserved_names']
                                , $GLOBALS['boardurl'] //$GLOBALS
                                , $txt['default_time_format']
                                , $txt['default_smileyset_name']
                                , $txt['default_classic_smileyset_name']
                                , $GLOBALS['modSettings']['databaseSession_enable'] //$GLOBALS
                                , $txt['default_smiley_smiley']
                                , $txt['default_wink_smiley']
                                , $txt['default_cheesy_smiley']
                                , $txt['default_grin_smiley']
                                , $txt['default_angry_smiley']
                                , $txt['default_sad_smiley']
                                , $txt['default_shocked_smiley']
                                , $txt['default_cool_smiley']
                                , $txt['default_huh_smiley']
                                , $txt['default_roll_eyes_smiley']
                                , $txt['default_tongue_smiley']
                                , $txt['default_embarrassed_smiley']
                                , $txt['default_lips_sealed_smiley']
                                , $txt['default_undecided_smiley']
                                , $txt['default_kiss_smiley']
                                , $txt['default_cry_smiley']
                                , $txt['default_evil_smiley']
                                , $txt['default_azn_smiley']
                                , $txt['default_afro_smiley']
                                , $txt['default_theme_name']
                                , $txt['default_classic_theme_name']
                                , $txt['default_babylon_theme_name']);
                                */

      
    }
    
 
    function updateFileSqlInstall($aPattern, $aReplace, $string)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $query =  $this->getInsertRvThemedata();
        $string .= $query;    
         //REPLACE TABLE NAME
        $string = str_replace($aPattern, $aReplace,$string);
        //REPLACE CREATE TABLE AND INSERT INTO
        $adataPatReplace = $this->getPattenAndgetReplaceCreateTableAndInsert();
        $string = str_replace($adataPatReplace['patten'], $adataPatReplace['replace'], $string);
        // warning file permission SGL_Config::get('path.webRoot') . '/forums
        $pathInstallComplete = SGL_Config::get('path.webRoot') . '/forums/installcomplete.sql';
        
        $fh = fopen($pathInstallComplete, 'w');
        $string = str_replace('<RVS>\n</RVS>', '', $string);
        fwrite($fh, $string);
        fclose($fh);
        
        return true;
    }
 
    function getPattenAndgetReplaceCreateTableAndInsert()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aPattenCreateAndInsert = array();
        $aReplaceCreateAndInsert = array();
        $adataPatReplace = array();
        $aPattenCreateAndInsert = array('CREATE TABLE', 'INSERT INTO');
        $aReplaceCreateAndInsert = array('create table if not exists' , 'REPLACE INTO');
        $adataPatReplace = array();
        $adataPatReplace['patten'] = $aPattenCreateAndInsert;
        $adataPatReplace['replace'] = $aReplaceCreateAndInsert;
        
        return $adataPatReplace;
    }
    
    
    /**
     * return SQL command insert 
     *
     * @return unknown
     */
    function getInsertRvThemedata()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
       $query ='#RVS insert theme data\n
INSERT INTO {$db_prefix}themes
	(ID_THEME, variable, value)
VALUES (17, \'name\', \'Rvtheme Theme\'),
	(17, \'theme_url\', \'{$boardurl}/Themes/rvtheme\'),
	(17, \'images_url\', \'{$boardurl}/Themes/default/images\'),
	(17, \'theme_dir\', \'{$boarddir}/Themes/rvtheme\');  
	       
REPLACE INTO {$db_prefix}settings
 (variable, value)
 VALUES 
(\'theme_default\', \'17\'),
(\'theme_guests\', \'17\');
	';
   //$result = $this->dbh->query($query);
   return $query;
    }
    
    /**
     * defind pattern to replace value in index.php , SSI.php
     *
     * @return unknown
     */
    function getPatternAndReplaceToFileIndexAndFileSsi()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        //match file index
        //for 1.1// Make sure some things simply do not exist.'
        $aPattenFileIndex = array('define(\'SMF\', 1);'
                                , '// And important includes.'
                                , 'ob_start('
                                , '// Check if the user should be disallowed access.'
                                , 'require_once(dirname(__FILE__) . \'/Settings.php\');');
                                
        $aReplaceFileIndex = array('define(\'SMF\', 1);
    // Seagull MOD: Load rvsStaticWeb
	define(\'RVS_COMPONENT_NAME\', \'forums\');
	if (is_file(dirname(dirname($_SERVER[\'SCRIPT_FILENAME\'])) . \'/rvsStaticWeb.php\')) {
		require_once  dirname(dirname($_SERVER[\'SCRIPT_FILENAME\'])) . \'/rvsStaticWeb.php\';
	}'
, '	// Seagull MOD: Load rvSettings
	if (file_exists(dirname(__FILE__) . \'/rvSettings.php\')) {
		require_once(dirname(__FILE__) . \'/rvSettings.php\');
	}
	// And important includes.'
, '	if (!defined(\'USE_RVSSEAGULL_MODE\'))
        ob_start('
, '	// Check if the user should be disallowed access.
    if (isset($_REQUEST[\'action\']) && $_REQUEST[\'action\'] == \'dlattach\' && (!empty($modSettings[\'allow_guestAccess\']) && $user_info[\'is_guest\'])) {
	// Seagull MOD: Automatic change theme
	   $settings[\'theme_dir\'] = \'rvtheme\';
	}
	'
, 'require_once(dirname(__FILE__) . \'/Settings.php\');
   require_once(dirname(__FILE__) . \'/rvSettings.php\');'
);
       // match file SSI.php
       $aPattenFileSsi = array('// Don\'t do john didley if the forum\'s been shut down competely.'
       , ' // Load the important includes.'
       , '// Check if the user should be disallowed access.'
       , 'ob_start('
       , 'require(dirname(__FILE__) . \'/Settings.php\');');
       
       $aReplaceFileSsi = array('// Seagull MOD: Load rvSettings
	if (file_exists(dirname(__FILE__) . \'/rvSettings.php\')) {
		require_once(dirname(__FILE__) . \'/rvSettings.php\');
	}

	// Don\'t do john didley if the forum\'s been shut down competely.'
	, '// Seagull MOD: Load rvSettings
    if (file_exists(dirname(__FILE__) . \'/rvSettings.php\')) {
        require_once(dirname(__FILE__) . \'/rvSettings.php\');
    }
    // Load the important includes.'
    , '// Check if the user should be disallowed access.
    if (isset($_REQUEST[\'action\']) && $_REQUEST[\'action\'] == \'dlattach\' && (!empty($modSettings[\'allow_guestAccess\']) && $user_info[\'is_guest\'])) {
    // Seagull MOD: Automatic change theme
       $settings[\'theme_dir\'] = \'rvtheme\';
    }'
    , 'if (!defined(\'USE_RVSSEAGULL_MODE\'))
        ob_start('
     , 'require(dirname(__FILE__) . \'/Settings.php\');
        require_once(dirname(__FILE__) . \'/rvSettings.php\');');

        $aDataReplace = array();
        $aDataReplace['PattenFileIndex'] = $aPattenFileIndex;
        $aDataReplace['ReplaceFileIndex'] = $aReplaceFileIndex;
        $aDataReplace['PattenFileSsi'] = $aPattenFileSsi;
        $aDataReplace['ReplaceFileSsi'] = $aReplaceFileSsi;
        /*echo "<pre>";
        print_r($aDataReplace);
		*/
        return $aDataReplace ;
    }
    
   function getaPattanAndaReplaceFileLoad()
   {
    $aPattan = array();
    $aReplace = array();
    $aPattan = array('// UTF-8 in regular expressions is unsupported on PHP(win) versions < 4.2.3.');
    $aReplace = array('// SEAGULL MOD: Disable security
    if(defined(\'USE_RVSSEAGULL_MODE\')) {
   $modSettings[\'registration_method\'] = 3;  
   $modSettings[\'securityDisable\'] = 1;
   $modSettings[\'enableVBStyleLogin\'] = 0;
   $modSettings[\'disableHostnameLookup\'] = 1;
   }

   // UTF-8 in regular expressions is unsupported on PHP(win) versions < 4.2.3.');
    $aData = array();
    $aData['aPattan'] = $aPattan;
    $aData['aReplace'] = $aReplace;
    return $aData;
    
   }
   
   function getaPattanAndaReplaceFileSubsMembers()
   {
        $aPattan = array();
        $aReplace = array();
        $aPattan = array('// If it\'s not an array, make it so!'
                            ,'// We\'ll need some external functions.');
        $aReplace = array('// SEAGULL MOD :: return if  run at seagull module
   if(defined(\'USE_RVSSEAGULL_MODE\')) {
       return;
   }

   // If it\'s not an array, make it so!
    '
                         ,'// SEAGULL MOD :: return if  run at seagull module
   if(defined(\'USE_RVSSEAGULL_MODE\')) {
      return;
   }

   // We\'ll need some external functions.');
                         
      $aData = array();
      $aData['aPattan'] = $aPattan;
      $aData['aReplace'] = $aReplace;
      return $aData; 
                         
   }
    
   function getaPattanAndaReplaceFileinstall()
   {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
       $aPattan = array();
       $aReplace = array();
       $aPattan = array('define(\'SMF\', 1);');

       $aReplace = array('define(\'SMF\', 1);

// Seagull MOD: define component name
if (!defined(\'RVS_COMPONENT_NAME\'))
 define(\'RVS_COMPONENT_NAME\', \'forums\');
 
 if (is_file(dirname(dirname($_SERVER[\'SCRIPT_FILENAME\'])) . \'/rvsStaticWeb.php\')) {
     require_once  dirname(dirname($_SERVER[\'SCRIPT_FILENAME\'])) . \'/rvsStaticWeb.php\';
 }');
        
       $aData = array();
       $aData['aPattan'] = $aPattan;
       $aData['aReplace'] = $aReplace;
       return $aData;
        
   }
   
   function getaPattanAndaReplaceFileIndexAttachment()
   {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
       $aPattan = array();
       $aReplace = array();
       $aPattan = array('require(dirname(dirname(__FILE__)) . \'/Settings.php\');');

       $aReplace = array('require(dirname(dirname(__FILE__)) . \'/Settings.php\');
                        require_once(dirname(dirname(__FILE__)) . \'/rvSettings.php\');');
        
       $aData = array();
       $aData['aPattan'] = $aPattan;
       $aData['aReplace'] = $aReplace;
       return $aData;
        
   }
   
    function checkFileInstallComplete()
    {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
       $pathInstallComplete = SGL_Config::get('path.webRoot') . '/forums/installcomplete.sql';
        if(is_file($pathInstallComplete)) {
          return true;
        }
        return false;
    }
    

    /**
     * modify Settings.php 
     * remove redirect install.php
     *
     * @param unknown_type $fileSetting
     * @return true/false
     */
    function updateFileSettings($fileSetting)
    {
    	SGL::logMessage(null,PEAR_LOG_DEBUG);
        $pathSF = file($fileSetting);
        $str  = "";
        foreach ($pathSF as $k => $line) {
            if (preg_match('/\/install.php|header\(\'Location/i', $line)) {
                $line = "";
            }
            $str .= $line;
        }
        //open to write
        if ($str) {
            if ($handle = fopen($fileSetting, 'w')) {
                fwrite($handle, $str);
                fclose($handle);
            } else {
                return false;
            }
            return true;
        }
    }

    /**
     * modify index.php
     * modify SSI.php
     * for run forums integrate with out seagull _mod
     *
     * @param unknown_type $patten
     * @param unknown_type $Replace
     * @param unknown_type $file
     * @return unknown
     */
    function updateFileIndexAndFileSsi($patten, $Replace, $file)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aLine = file($file);

        $string = implode("\n", $aLine);
        if (preg_match('/Seagull\s*MOD/i', $string)) {
            return true;
        }
        //index.php,SSI.php
        if($fh = fopen($file, 'w')) {
            //if($data = fread($fh, filesize($file))) {
            foreach ($aLine as $line) {
                $line = str_replace($patten, $Replace, $line);
                fwrite($fh, $line);
            }
            fclose($fh);
        } else {
            echo "<h3>Cannot open: " . $file  . '</h3>';
        }
        return true;
    }
    
    function isForumsSupportLang($langId)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        include SGL_MOD_DIR . '/forums/lang/ary.languages.php';
        if (isset($aLangConf[$langId])) {
            return true;
        }
        return false;
    }
    
    
    function isLang($langDefaultPath,$langId,$langPublishPath, $langName)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	include SGL_MOD_DIR . '/forums/lang/ary.languages.php';
    	//require_once SGL_Config::get('path.webRoot') . '/forums/rvSettings.php';   	
    	$boarddir = SGL_Config::get('path.webRoot') . '/forums';
    	//$obLang = &sglLangConfig::singleton();
    	$langUTF = ($langId != 'en') ? '-utf8' : '';
    	$langFileName 	= (isset($aLangConf[$langId])) ? $aLangConf[$langId][0] . $langUTF : $langName;

    	$dh 			  = opendir($langDefaultPath);
    	$aFileDefaultLang = array();
    	if ($dh) {
    		while (false !== ($file = readdir($dh))) {
    			$strF = (preg_match("/(english)/", $file)) ? $file : false;
    			if ($strF) {
    				$aFileDefaultLang[] = $strF;
    			}
    		}
    		closedir($dh);
    	}
    	if (preg_match ( "/(english)/", $langFileName ) == true ) {
    		return true;
    	}
    	 
    	if (count($aFileDefaultLang)) {
    	    foreach ($aFileDefaultLang as $file) {
    	        $langlocal	=	str_replace('utf-8','utf8',$langFileName);
    	        $file 		= 	str_replace('english',$langlocal, $file);//'thai-utf8'
    	        if (!is_file($langPublishPath . '/' . $file)) {
    	            return false;
    	        }
    	    }
    	} else {
    	    return false;
    	}
    	return true;
    }
    
    function getLangNameForums($langId)
    {
        include SGL_MOD_DIR . '/forums/lang/ary.languages.php';
        if (isset($aLangConf[$langId][0])) {
            return $aLangConf[$langId][0];
        }
        return 'english';
    }
    
    function addTableForumsToFileConfig()
    {
    	SGL::logMessage(null,PEAR_LOG_DEBUG);
    	$pathInstallComplete =SGL_Config::get('path.webRoot') . '/forums/installcomplete.sql';
    	$aLine = file($pathInstallComplete);
    	$aTable = array();
    	foreach ($aLine as $line) {
    		if (preg_match("/CREATE\s*TABLE\s*IF\s*NOT\s*EXISTS(.*?)\(|CREATE\s*TABLE\s*(.*?)\(/i", $line, $aMatch)) {
    			$aTable[] = trim($aMatch[1]);
    		}
    	}
    	$c = &SGL_Config::singleton();
    	$c->merge($this->conf);
    	
    	$dbPrefix = SGL_Config::get('db.prefix'); // get data from MainIP.conf.php
    	$fw = fopen(SGL_Config::get('path.webRoot') . '/forums/tableAliases.ini','w');
    	//var_dump($fw);
    	foreach ($aTable as $tableName) {
    		$tableNameWithPrefix = trim($dbPrefix) . trim($tableName);
    		$c->set('table', array(trim($tableName) => $tableNameWithPrefix));
    		fwrite($fw,"{$tableName}={$tableName}\n");
    	}
    	fclose($fw);
    	$ok = $c->save(); // save file MainIP.conf.php
    	if (!$ok) {
    		return false;
    	}
    	return true;
    }

    
    function _isOriginalPassword($passwd)
    {
    	SGL::logMessage(null,PEAR_LOG_DEBUG);
        if (isset($passwd)) {
            $oUser = DB_DataObject::factory($this->conf['table']['user']);
            $oUser->get(SGL_Session::getUid());
            if (md5($passwd) == $oUser->passwd) {
                return true;
            }
        }
        return false;
    }
    
    function deleteFileInstall()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $pathInstall = SGL_Config::get('path.webRoot') . '/forums/install.php';
        if(is_file($pathInstall) && is_writable($pathInstall)) {
            unlink($pathInstall);
            return true;
        }
        return false;
    }
    

}
?>