<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class ModSite extends Module {
    
	protected $_filters = array(
        'check_admin' => ''
    );
	
    public function admin_list() {
    	$this->_layout = 'content';
    	
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_site/_LOCALE', $curr_locale));
        $lang_sw = trim(ParamHolder::get('lang_sw', $mod_locale));
        SessionHolder::set('mod_site/_LOCALE', $lang_sw);
        
        $o_siteinfo = new SiteInfo();
        $curr_siteinfo =& $o_siteinfo->find("s_locale=?", array($lang_sw));
        
        $this->assign('curr_siteinfo', $curr_siteinfo);
        
        $this->assign('lang_sw', $lang_sw);
        $this->assign('langs', Toolkit::loadAllLangs());
        
        try {
			$curr_locale = trim(SessionHolder::get('_LOCALE'));
			$mod_locale = trim(SessionHolder::get('mod_static/_LOCALE', $curr_locale));
			$lang_sw = trim(ParamHolder::get('lang_sw', $mod_locale));
			SessionHolder::set('mod_static/_LOCALE', $lang_sw);
			if(strtolower($lang_sw) == 'zh_cn') {
				$cus_id = 1;
			} else if(strtolower($lang_sw) == 'en'){
				$cus_id = 3;
			}
            $curr_cus = new StaticContent($cus_id);
            $this->assign('curr_cus', $curr_cus);

			if(strtolower($lang_sw) == 'zh_cn') {
				$co_id = 2;
			} else if(strtolower($lang_sw) == 'en') {
				$co_id = 4;
			}
            $curr_co = new StaticContent($co_id);
            $this->assign('curr_co', $curr_co);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }
        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('lang_sw', $lang_sw);
		//logo banner foot
		$o_mb = new ModuleBlock();
		$curr_logo = $o_mb->find("s_locale=? and alias=? and module=? and action=?",array($lang_sw,'mb_logo','mod_media','show_image'));
		$this->assign('curr_logo', $curr_logo);
		$this->assign('p_logo', unserialize($curr_logo->s_param));
		//
		$curr_banner = $o_mb->find("s_locale=? and alias=? and module=?",array($lang_sw,'mb_banner','mod_media'));
		$this->assign('curr_banner', $curr_banner);
		$this->assign('p_banner', unserialize($curr_banner->s_param));
		//
		$curr_foot = $o_mb->find("s_locale=? and alias=? and module=? and action=?",array($lang_sw,'mb_foot','mod_static','custom_html'));
		$this->assign('curr_foot', $curr_foot);
		$this->assign('p_foot', unserialize($curr_foot->s_param));
    }
    
    public function save_info() {
		$this->_layout = 'content';

        $site_param =& ParamHolder::get('sparam', array());
        $site_info =& ParamHolder::get('si', array());
        $cus_info =& ParamHolder::get('cus', array());
		$co_info =& ParamHolder::get('co', array());
		$isLink = & ParamHolder::get('isLink', array());
		$LinkAddr = & ParamHolder::get('LinkAddr', array());
		
    	if (sizeof($cus_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing contact us information!')));
            return '_result';
        }
        if (sizeof($site_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing site information!')));
            return '_result';
        }
    	if (!isset($site_param['AUTO_LOCALE'])) {
            $site_param['AUTO_LOCALE'] = '0';
        }
        if (!isset($site_param['SITE_OFFLINE'])) {
            $site_param['SITE_OFFLINE'] = '0';
        }
    	if (!isset($site_param['SITE_LOGIN_VCODE'])) {
            $site_param['SITE_LOGIN_VCODE'] = '0';
        }
    	if (!isset($site_param['USE_LANGUAGE'])) {
            $site_param['USE_LANGUAGE'] = SessionHolder::get('_LOCALE');
        }
        try {
            // Data operation
            $o_siteinfo = new SiteInfo();
            $curr_siteinfo =& $o_siteinfo->find("s_locale=?", array($site_info['s_locale']));
            if (intval($site_info['id']) != intval($curr_siteinfo->id)) {
	            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
	            return '_result';
            }
            if ($curr_siteinfo) {
	            $curr_siteinfo->set($site_info);
	            $curr_siteinfo->save();
            } else {
                $o_siteinfo->set($site_info);
                $o_siteinfo->save();
            }
			//add 2010-6-27 rewrite
			if($site_param['MOD_REWRITE'] == 2) {
				$htaccess = "RewriteEngine On \n";
				$htaccess .= 'RewriteBase /'.substr(ROOT,strlen($_SERVER['DOCUMENT_ROOT'])+1)."/ \n";
				$htaccess .= "RewriteCond %{REQUEST_FILENAME} !-f \n";
				$htaccess .= "RewriteCond %{REQUEST_FILENAME} !-d \n";
				$htaccess .= 'RewriteRule ([a-zA-Z_]{1,})-([a-zA-Z_]{1,}).html$ index.php?_m=$1&_a=$2'." \n";
				$htaccess .= 'RewriteRule ([a-zA-Z_]{1,})-([a-zA-Z_]{1,})-([a-zA-Z_]{1,})-([0-9]{1,}).html$ index.php?_m=$1&_a=$2&$3=$4'." \n";
				$htaccess .= 'RewriteRule ([a-zA-Z_]{1,})-([a-zA-Z_]{1,})-([a-zA-Z_]{1,})-([0-9]{1,})-([a-zA-Z_]{1,})-([0-9]{1,}).html$ index.php?_m=$1&_a=$2&$3=$4&$5=$6'." \n";				
				$admin_htaccess = "RewriteEngine On \n";
				$admin_htaccess .= 'RewriteBase /'.substr(ROOT,strlen($_SERVER['DOCUMENT_ROOT'])+1)."/admin/ \n";
				$admin_htaccess .= "RewriteCond %{REQUEST_FILENAME} !-f \n";
				$admin_htaccess .= "RewriteCond %{REQUEST_FILENAME} !-d \n";
				$admin_htaccess .= 'RewriteRule ([a-zA-Z_]{1,})-([a-zA-Z_]{1,}).html$ index.php?_m=$1&_a=$2'." \n";
				$admin_htaccess .= 'RewriteRule ([a-zA-Z_]{1,})-([a-zA-Z_]{1,})-([a-zA-Z_]{1,})-([0-9]{1,}).html$ index.php?_m=$1&_a=$2&$3=$4'." \n";
				file_put_contents(ROOT.'/.htaccess',$htaccess);
				file_put_contents(ROOT.'/admin/.htaccess',$admin_htaccess);
			} else {
				file_put_contents(ROOT.'/.htaccess','');
				file_put_contents(ROOT.'/admin/.htaccess','');
			}
            $o_param = new Parameter();
        	foreach ($site_param as $key => $val) {
        	    $param =& $o_param->find('`key`=?', array($key));
        	    if ($param) {
        	        $param->val = $val;
        	        $param->save();
        	    }
        	}
        	
        	//save language
        	$curr_lang = new Language($site_param['USE_LANGUAGE']+1);
            $o_param = new Parameter();
            $locale_param =& $o_param->find("`key`='DEFAULT_LOCALE'");
            $locale_param->val = $curr_lang->locale;
            $locale_param->save();
            SessionHolder::set('_LOCALE', $curr_lang->locale);

            $cus_info['create_time'] = time();
			
            $cus_info['published'] = 1;
            $cus_info['title'] = __('AboutUs');
			$cus_info['for_roles'] = '{member}{admin}{guest}';

			$linkFlag = false;
            $linkValue = $o_param->find("`key` = 'BANNER_ISLINK'");
	        if(empty($isLink) || ($isLink == 'no'))
			{
				$linkValue->val = 'no';
			}
			else
			{
				$linkFlag = true;
				$linkValue->val = 'yes';
			}
            $linkValue->save();
            
            if($linkFlag)
            {
            	$linkAddr1 = $o_param->find("`key` = 'BANNER_LINK_ADDR'");
            	$pos1 = strpos($LinkAddr,'http:');
            	$pos2 = strpos($LinkAddr,'http://');
            	if(($pos1 === false) && ($pos2 == false))
            	{
            		if(!empty($LinkAddr))
            		{
            			$LinkAddr = 'http://'.$LinkAddr;
            		}
            		else
            		{
            			$LinkAddr = '#';
            		}
            	}
            	
            	$linkAddr1->val = $LinkAddr;
            	$linkAddr1->save();
            }
            
			
            $o_cus = new StaticContent($cus_info['id']);
            $o_cus->set($cus_info);
            $o_cus->save();

			$co_info['create_time'] = time();
			
            $co_info['published'] = 1;
            $co_info['title'] = __('ContactUs');
			
            $o_o = new StaticContent($co_info['id']);
            $o_o->set($co_info);
            $o_o->save();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_result';
        }
    
        $flag_flash = false;
		$curr_locale = trim(SessionHolder::get('_LOCALE'));
		$mod_locale = trim(SessionHolder::get('mod_static/_LOCALE', $curr_locale));
		$lang_sw = trim(ParamHolder::get('lang_sw', $mod_locale));
	
		$logo_info =& ParamHolder::get('logo', array());
		$param_info =& ParamHolder::get('param', array());
		$logo_file =& ParamHolder::get('logo_file', array(), PS_FILES);
		$play_info =& ParamHolder::get('radio', array());
		
			$logo_arr = array();
			$logo_info['module'] = 'mod_media';
			$logo_info['action'] = 'show_image';
			$logo_info['alias'] = 'mb_logo';
			$logo_info['title'] = '';
			$logo_info['show_title'] = 0;
			$logo_info['s_pos'] = 'logo';
			$logo_info['s_locale'] = $lang_sw;
			$logo_info['s_query_hash'] = '_ALL';
			$logo_info['i_order'] = 0;
			$logo_info['published'] = 1;
			
			$logo_info['for_roles'] = '{member}{admin}{guest}';
			if($logo_file['name']) {//有此图片上传
				if(!preg_match('/\.('.PIC_ALLOW_EXT.')$/i', $logo_file["name"])) {
					Notice::set('mod_static/msg', __('File type error!'));
					die(__('File type error!'));
					Content::redirect(Html::uriquery('mod_static', 'admin_mod'));
				}
				if(file_exists(ROOT.'/upload/image/'.$logo_file["name"])) {
					$logo_file["name"] = Toolkit::randomStr(8).strrchr($logo_file["name"],".");
				}
				if (!$this->_savelinkimg($logo_file)) {
					Notice::set('mod_static/msg', __('Link image upload failed!'));
					Content::redirect(Html::uriquery('mod_static', 'admin_mod'));
				}
				$logo_arr['img_src'] = 'upload/image/'.$logo_file["name"];
				$xml = new DOMDocument('1.0','utf-8');
				$xml->load('SitestarMaker/SitestarMaker.xml');
				$xml->getElementsByTagName('custom')->item(0)->nodeValue = 'no';
				$xml->save('SitestarMaker/SitestarMaker.xml');
				/**
				 * 删除编辑前的对应图片文件
				 */
				 if (file_exists(ROOT.'/'.$param_info['logo_img'])) {
				 	 unlink(ROOT.'/'.$param_info['logo_img']);
				 }
			} else {//无此图片上传
				$logo_arr['img_src'] = $param_info['logo_img'];
			}
			$logo_arr['img_desc'] = '';
			$logo_arr['img_width'] = $param_info['logo_width'];
			$logo_arr['img_height'] = $param_info['logo_height'];
			$logo_info['s_param'] = serialize($logo_arr);
			if(!$logo_info['id']){
				$o_logo = new ModuleBlock();
				$o_logo->set($logo_info);
				$o_logo->save();
			} else {//无论有无图片上传,走次
				 $o_logo = new ModuleBlock($logo_info['id']);
				 $o_logo->set($logo_info);
				 $o_logo->save();
			}
		
		$banner_info =& ParamHolder::get('banner', array());
		$banner_file =& ParamHolder::get('banner_file', array(), PS_FILES);
		if(!empty($banner_file['name']))
		{
			$xml = new DOMDocument('1.0','utf-8');
			$xml->load('SitestarMaker/SitestarMaker.xml');
			$xml->getElementsByTagName('banner1_custom')->item(0)->nodeValue = 'no';
			$xml->save('SitestarMaker/SitestarMaker.xml');
			$banner_arr = array();
			$banner_info['module'] = 'mod_media';
			$banner_info['action'] = 'show_image';
			if(strpos($banner_file['name'],'swf'))
			{
				$banner_info['action'] = 'show_flash';
				$flag_flash = true;
			}
			$banner_info['alias'] = 'mb_banner';
			$banner_info['title'] = '';
			$banner_info['show_title'] = 0;
			$banner_info['s_pos'] = 'banner';
			$banner_info['s_locale'] = $lang_sw;
			$banner_info['s_query_hash'] = '_ALL';
			$banner_info['i_order'] = 0;
			$banner_info['published'] = 1;
			
			$banner_info['for_roles'] = '{member}{admin}{guest}';
			if($banner_file['name']) {
				$pic_allow_ext = PIC_ALLOW_EXT.'|swf';
				if(!preg_match('/\.('.$pic_allow_ext.')$/i', $banner_file["name"])) {
					Notice::set('mod_static/msg', __('File type error!'));
					die(__('File type error!'));
					Content::redirect(Html::uriquery('mod_static', 'admin_mod'));
				}
				
				if($flag_flash)
				{
					if(file_exists(ROOT."/upload/flash/".$banner_file["name"])) {
						$banner_file["name"] = Toolkit::randomStr(8).strrchr($banner_file["name"],".");
					}
					if (!$this->_savelinkflash($banner_file)) {
						Notice::set('mod_static/msg', __('Link flash upload failed!'));
						Content::redirect(Html::uriquery('mod_static', 'admin_mod'));
					}
					$banner_arr['flv_src'] = 'upload/flash/'.$banner_file["name"];
				}
				else
				{
					if(file_exists(ROOT.'/upload/image/'.$banner_file["name"])) {
						$banner_file["name"] = Toolkit::randomStr(8).strrchr($banner_file["name"],".");
					}
					if (!$this->_savelinkimg($banner_file)) {
						Notice::set('mod_static/msg', __('Link image upload failed!'));
						Content::redirect(Html::uriquery('mod_static', 'admin_mod'));
					}
					$banner_arr['img_src'] = 'upload/image/'.$banner_file["name"];
				}
				/**
				 * 编辑模式下删除编辑前的对应图片文件
				 */
				if (file_exists(ROOT.'/'.$param_info['del_banner_img'])) {unlink(ROOT.'/'.$param_info['del_banner_img']);}
			} else {
				$banner_arr['img_src'] = $param_info['banner_img'];
			}
				$banner_arr['img_desc'] = '';
				$banner_arr['flv_width'] = $banner_arr['img_width'] = $param_info['banner_width'];
				$banner_arr['flv_height'] = $banner_arr['img_height'] = $param_info['banner_height'];
				$banner_info['s_param'] = serialize($banner_arr);
				
				if(!$banner_info['id']){
					$o_banner = new ModuleBlock();
					$o_banner->set($banner_info);
					$o_banner->save();
				} else {
					$o_banner = new ModuleBlock($banner_info['id']);
					 $o_banner->set($banner_info);
					 $o_banner->save();
				}
		}
		elseif(empty($banner_file['name']) && !empty($param_info))
		{
			$o_mb = new ModuleBlock();
			$curr_banner = $o_mb->find("s_locale=? and alias=? and module=?",array($lang_sw,'mb_banner','mod_media'));
			$arr = unserialize($curr_banner->s_param);
			$banner_arr['img_desc'] = '';
			$banner_arr['flv_width'] = $banner_arr['img_width'] = $param_info['banner_width'];
			$banner_arr['flv_height'] = $banner_arr['img_height'] = $param_info['banner_height'];
			if($arr['flv_src']){
				$banner_arr['flv_src'] = $arr['flv_src'];
			}else{
				$banner_arr['img_src'] = $arr['img_src'];
			}
			$banner_info['s_param'] = serialize($banner_arr);
			$o_banner = new ModuleBlock($banner_info['id']);
			$o_banner->set($banner_info);
			$o_banner->save();
		}
		
		$foot_info =& ParamHolder::get('foot', array());
		$foot_arr = array();
		$foot_info['module'] = 'mod_static';
		$foot_info['action'] = 'custom_html';
		$foot_info['alias'] = 'mb_foot';
		$foot_info['title'] = '';
		$foot_info['show_title'] = 0;
		$foot_info['s_pos'] = 'footer';
		$foot_info['s_locale'] = $lang_sw;
		$foot_info['s_query_hash'] = '_ALL';
		$foot_info['i_order'] = 0;
		$foot_info['published'] = 1;
		
		$foot_info['for_roles'] = '{member}{admin}{guest}';
		
		$foot_arr['html'] = $param_info['html'];
		$foot_info['s_param'] = serialize($foot_arr);
		
		if(!$foot_info['id']){
			$o_foot = new ModuleBlock();
            $o_foot->set($foot_info);
            $o_foot->save();
		} else {
			$o_foot = new ModuleBlock($foot_info['id']);
			$o_foot->set($foot_info);
			$o_foot->save();
		}
		
		$music_file =& ParamHolder::get('music_file', array(), PS_FILES);
		if(!empty($music_file['name'])) {
			if($music_file['size'] == 0){
//				die(__('Upload file exceed size limit!'));
				$msg = __('Upload file exceed size limit!');$msg = "<b style='color:red;'>$msg</b>";
				Notice::set('mod_site/msg', $msg);
				Content::redirect(Html::uriquery('mod_site', 'admin_list'));
			}
			
			if(!preg_match('/\.('.MUSIC_ALLOW_EXT.')$/i', $music_file["name"])) {
				Notice::set('mod_static/msg', __('File type error!'));
				die(__('File type error!'));
			}
			if(file_exists(ROOT.'/upload/media/'.$music_file["name"])) {
				$show_name = $music_file["name"];
				$music_file["name"] = Toolkit::randomStr(8).strrchr($music_file["name"],".");
			}else {
				$show_name = $music_file["name"];
			}
			if (!$this->_savelinkmusic($music_file)) {
				Notice::set('mod_static/msg', __('Link music upload failed!'));
				Content::redirect(Html::uriquery('mod_static', 'admin_mod'));
			}
			$music_arr['BG_MUSIC'] = 'upload/media/'.$music_file["name"];
			$o_bgmusic = new BackgroundMusic();
			$bgmusic_items = $o_bgmusic->findAll();
			$db = MysqlConnection::get();
			$prefix = Config::$tbl_prefix;
			if(empty($bgmusic_items)) {
				$sql = <<<SQL
INSERT INTO {$prefix}background_musics VALUES(1,'{$music_arr['BG_MUSIC']}',{$play_info['play_type']},'{$music_file["name"]}')	
SQL;
			} else {
				$music_path = iconv("UTF-8", "gb2312", $bgmusic_items[0]->music_path);
				if(file_exists(ROOT.'/'.$music_path)) {
					unlink(ROOT.'/'.$music_path);
				}
				$sql = <<<SQL
UPDATE {$prefix}background_musics SET `music_path` = '{$music_arr['BG_MUSIC']}',`music_name` = '$show_name',`play` = {$play_info['play_type']} WHERE `id` = '{$bgmusic_items[0]->id}'		
SQL;
			}
			$result = $db->query($sql);
		}else {
			$o_bgmusic = new BackgroundMusic();
			$bgmusic_items = $o_bgmusic->findAll();
			if(!empty($bgmusic_items)) {
				$db = MysqlConnection::get();
				$prefix = Config::$tbl_prefix;
				$sql = <<<SQL
UPDATE {$prefix}background_musics SET `play` = {$play_info['play_type']} WHERE `id` = '{$bgmusic_items[0]->id}'		
SQL;
				$result = $db->query($sql);
			}
		}
   		Content::redirect("index.php?_m=mod_site&_a=admin_list&_r=_page"); 

    }
    
    public function reset_tpl_data() {
        $db =& MySqlConnection::get();
        $client =& Toolkit::initSoapClient();
        $sqls = unserialize($client->getTplSampleData_SSv2(DEFAULT_TPL, EZSITE_LEVEL));
        if ($sqls == 'ERROR') {
            $this->assign('json', Toolkit::jsonERR(__('Invalid template!')));
            return '_result';
        }
        
        foreach ($sqls as $sql) {
            $db->query($sql);
        }
        
        $this->assign('json', Toolkit::jsonOK());
        return '_result';
    }
	public function admin_dat() {
		$this->_layout = 'dat';
		
		$domain = Toolkit::getSubDomain($_SERVER['HTTP_HOST']);
		$key = sha1($domain."ssiuhIUAHSiu!husashu11dd@kjdjsah==");
		$str = file_get_contents('http://licence.sitestar.cn/licencedat.php?domain='.trim($domain).'&key='.$key);
		if($str=='1002'){
			Content::redirect(Html::uriquery('mod_site', 'licence'));
		}else if($str!='1001') {
			$dat = '<?php '.$str.' ?>';
			file_put_contents('../licence.dat', $dat);
		}

		Content::redirect(Html::uriquery('frontpage', 'dashboard'));
	}
	public function licence() {
		$this->_layout = 'dat';
		$this->assign('curr_banner', 111);
	}
	public function admin_dashboard() {
		$this->_layout = 'default';
	}
	
	private function _savelinkimg($struct_file) {
		$struct_file['name'] = iconv("UTF-8", "gb2312", $struct_file['name']);
        return move_uploaded_file($struct_file['tmp_name'], ROOT.'/upload/image/'.$struct_file['name']);
    }
    
    private function _savelinkflash($struct_file){
    	$struct_file['name'] = iconv("UTF-8", "gb2312", $struct_file['name']);
    	return move_uploaded_file($struct_file['tmp_name'], ROOT.'/upload/flash/'.$struct_file['name']);
    }
    
	private function _savelinkmusic($struct_file){
		$struct_file['name'] = iconv("UTF-8", "gb2312", $struct_file['name']);
    	return move_uploaded_file($struct_file['tmp_name'], ROOT.'/upload/media/'.$struct_file['name']);
    }
}
?>