<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Skins extends CI_Controller {

	function __construct(){
		parent::__construct();
        	$this->load->helper('url');
                $this->load->library('session'); //加载session
		$this->load->model('CsdjDB');
		$this->load->model('CsdjAdmin');
		$this->load->model('CsdjSkins');
                $this->db->cache_off();
	        $this->CsdjAdmin->Admin_Login();
                $this->load->helper('file');
	}


	public function index()
	{
 	    $sid = $this->input->get('sid');

            if($sid==1){
 	          $arrs['index'] = get_dir_file_info("./skins/index/", $top_level_only = TRUE);
            }elseif($sid==2){
 	          $arrs['home'] = get_dir_file_info("./skins/home/", $top_level_only = TRUE);
            }elseif($sid==3){
 	          $arrs['user'] = get_dir_file_info("./skins/user/", $top_level_only = TRUE);
            }else{
 	          $arrs['index'] = get_dir_file_info("./skins/index/", $top_level_only = TRUE);
 	          $arrs['home'] = get_dir_file_info("./skins/home/", $top_level_only = TRUE);
 	          $arrs['user'] = get_dir_file_info("./skins/user/", $top_level_only = TRUE);

            }

            $data['url']=site_url('admin/skins/index/')."?";
            $data['skins']=$arrs;
            $data['sid']=$sid;

            $this->load->view('admin/skins',$data);
        }

	public function lists()
	{
 	    $path = $this->input->get('path');
            if(empty($path)) $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，路径错误！</font>','javascript:history.back();');
                  if(substr($path,0,6)!='/skins'){
                        $this->CsdjAdmin->Admin_Url('<font color=red>参数错误，路径非法！</font>','javascript:history.back();');
                  }

                  if(!is_dir('.'.$path)){
                        $this->CsdjAdmin->Admin_Url('<font color=red>该模板文件不存在！</font>','javascript:history.back();');
                  }

                  $arrs=get_dir_file_info(".".$path, $top_level_only = TRUE);

                  $data['path']=$path;
                  $data['url']=site_url('admin/skins/index/')."?path=".$path;
                  $data['show']=$arrs;

                  if($path=="/skins/"){
                      $data['uppage']=site_url('admin/skins/lists/');
                  }else{
                      $data['uppage']="javascript:history.back();";
                  }
            $this->load->view('admin/skins_list',$data);
        }

	//安装
	public function install()
	{
            $this->CsdjAdmin->Admin_Qx('38');
	    $path=$this->input->get_post('path');
	    $dir=$this->input->get_post('dir');
	    $sid=$this->input->get_post('sid');
            if(empty($dir)) $this->CsdjAdmin->Admin_Url('<font color=red>参数错误，目录为空！</font>','javascript:history.back();');

            if($sid==3){
                  $paths='user';
                  $files='./skins/'.$path.'user-index.html';
            }elseif($sid==2){
	          $paths='home';
                  $files='./skins/'.$path.'home-index.html';
            }else{
	          $paths='index';
                  $files='./skins/'.$path.'cs-index.html';
            }

	    $file   = './skins/'.$paths.'/' . $dir . '/config.php';
	    if (!file_exists($file)) $this->CsdjAdmin->Admin_Url('<font color=red>模板缺少配置文件！</font>','javascript:history.back();');
            require_once $file;

            //判断模板路径
            if(!file_exists($files) || @$config['mid']==''){
                 $this->CsdjAdmin->Admin_Url('<font color=red>安装失败,没有找到模板文件！</font>','javascript:history.back();');
            }

	       //直接添加表中记录
               $updata['CS_Name']=$config['name'];
               $updata['CS_TempPath']=$path;
               $updata['CS_SID']=$sid;
               $this->CsdjDB->get_insert('skins',$updata);
               $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，安装成功！</font>',$_SERVER['HTTP_REFERER'],'ok');
        }

	//卸载
	public function uinstall()
	{
            $this->CsdjAdmin->Admin_Qx('38');
	        $id=$this->input->get_post('id');
            $this->CsdjDB->get_del('skins',$id);
            $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，卸载成功！</font>',$_SERVER['HTTP_REFERER'],'ok');
        }

	//删除
	public function deldir()
	{
            $this->CsdjAdmin->Admin_Qx('38');
	    $dir=$this->input->get_post('dir');
	    $sid=$this->input->get_post('sid');
            if(empty($dir)) $this->CsdjAdmin->Admin_Url('<font color=red>参数错误，目录为空！</font>','javascript:history.back();');

            if($sid==3){
                  $path='user';
            }elseif($sid==2){
	          $path='home';
            }else{
	          $path='index';
            }

	    $dirs   = './skins/'.$path.'/' . $dir;
	    if(!is_dir($dirs)){
                 $this->CsdjAdmin->Admin_Url('<font color=red>该模板目录不存在,删除失败！</font>','javascript:history.back();');
            }

	    $file   = './skins/'.$path.'/' . $dir . '/config.php';
	    if (!file_exists($file)) $this->CsdjAdmin->Admin_Url('<font color=red>模板缺少配置文件！</font>','javascript:history.back();');
            require_once $file;
            $row=$this->db->query("SELECT CS_ID FROM ".CS_SqlPrefix."skins where cs_sid='".$sid."' and CS_Name='".$config['name']."'")->row();
            if($row){
                  $this->CsdjDB->get_del('skins',$row->CS_ID);
            }
	       //直接删除模板目录
               $this->CsdjAdmin->deldir($dirs,'ok');
               $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，删除成功！</font>',site_url('admin/skins/index'),'ok');
        }

	/**
	 * 在线模板中心
	 */
	public function yun()
	{
	        $app['url']='http://'.Web_Url.Web_Path;
	        $app['site']=Web_Url;
	        $app['admin']=SELF;
	        $app['version']=CS_Version;
	        $app['charset']='gbk';
	        $app['uptime']=CS_Uptime;
            $plugins_api=CS_YPTURL."skins?param=".$this->cs_base64_encode($app);
            header("Location: ".$plugins_api.""); 
	}

	/**
	 * 模板下载
	 */
	public function down()
	{
            $mold=$this->input->get_post('mold');
            $dir=$this->input->get_post('dir');
            $mid=$this->input->get_post('mid');
            $sid=$this->input->get_post('sid');
            $key=$this->input->get_post('key');
	        if (empty($key) || empty($dir) || empty($mid) || empty($sid)){
				$this->CsdjAdmin->Admin_Url('<font color=red>抱歉，参数错误！</font>',site_url('admin/skins/yun/'));
			}
            if($sid==3){ //会员中心模板
                  $path='user';
            }elseif($sid==2){  //会员主页模板
	              $path='home';
            }else{   //主页模板
	              $path='index';
            }

	        $app['url']='http://'.Web_Url.Web_Path;
	        $app['site']=Web_Url;
	        $app['admin']=SELF;
	        $app['version']=CS_Version;
	        $app['charset']='gbk';
	        $app['uptime']=CS_Uptime;
	        $app['data']['key']=$key;
            $zip=CS_YPTURL."skins/down/".$mid."?param=".$this->cs_base64_encode($app);
            $zippath="./attachment/other/skins_".$dir.".zip";
            $testzip_path="./skins/".$path."/";
            $files_file=$this->CsdjAdmin->get_files_file($zip,$zippath);
    	    if ($files_file=='-1') $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，插件地址错误！</font>',site_url('admin/plugins/yun/'));
    	    if ($files_file=='-2') $this->CsdjAdmin->Admin_Url('<font color=red>对不起，您的服务器不支持远程下载,请开启CURL！</font>',site_url('admin/skins/yun/'));
    	    if ($files_file=='-3') $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，目录（./attachment/other/）没有写入权限！</font>',site_url('admin/skins/yun/'));
	        if (filesize($zippath) == 0) $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，模板下载失败！</font>',site_url('admin/skins/yun/'));

		    //解压缩
	        $this->load->model('PclZip');
		    $this->PclZip->PclZip($zippath);
		    if ($this->PclZip->extract(PCLZIP_OPT_PATH, $testzip_path, PCLZIP_OPT_REPLACE_NEWER) == 0) {
                    	@unlink($zippath);
                        $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，模板解压失败！</font>',site_url('admin/skins/yun/'));
		    }else{

		            if (!file_exists($testzip_path.$dir.'/config.php')) {
			                @unlink($zippath);
                            $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，模板不完整！</font>',site_url('admin/skins/yun/'));
			        }
			        @unlink($zippath);
                    $this->CsdjAdmin->Admin_Url('<font color=red>恭喜您，模板下载成功！</font>',site_url('admin/skins/index/'),'ok');
			}

	}

	public function res()
	{
            $this->load->view('admin/skins_res');
        }

	public function add()
	{
            $data['title']="新增模板文件";
            $data['title2']="新增";
            $data['path']="";
            $data['CS_Name']="";
            $data['CS_Neir']="";
            $this->load->view('admin/skins_edit',$data);
        }

	public function edit()
	{
 	    $path = $this->input->get('path');
 	    $filename = $this->input->get('name');
            if(empty($filename)) $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，文件错误！</font>','javascript:history.back();');
            if(empty($path) || substr($path,0,6)!='/skins') $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，路径错误！</font>','javascript:history.back();');

            $path='.'.$path;
	    if(!file_exists($path))  $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，文件不存在！</font>','javascript:history.back();');
            $neir=read_file($path);

            $data['title2']="修改";
            $data['title']="修改模板文件——“".$path."”";
            $data['path']=$path;
            $data['CS_Name']=str_replace('.html','',$filename);
            $data['CS_Neir']=str_replace('</textarea>','&lt;/textarea&gt;',$neir);
            $this->load->view('admin/skins_edit',$data);
        }

	public function pledit()
	{
            $this->CsdjAdmin->Admin_Qx('38');
 	    $CS_ID = $this->input->post('CS_ID');
            if(empty($CS_ID)) $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，请选择要操作的数据！</font>','javascript:history.back();');

            foreach ($CS_ID as $ID) {  //文件
 	        $CS_SID = $this->input->post('CS_SID'.$ID);
 	        $CS_IDS = $this->input->post('CS_IDS'.$CS_SID);
 	        $CS_Name = $this->input->post('CS_Name'.$ID);
 	        $CS_TempPath = $this->input->post('CS_TempPath'.$ID);

                if(!empty($CS_Name) && !empty($CS_TempPath)){
                     $data['CS_Name']=$CS_Name;
                     $data['CS_TempPath']=$CS_TempPath;
                     $this->CsdjDB->get_update('skins',$ID,$data);
                }

                //--------------------------设置默认模板---------------------------//

	        $str=read_file("./csdj/lib/Cs_Config.php"); 
                if($CS_SID==1){ //主站
	             $str=preg_replace('/"Skins_dir","(.*?)"/','"Skins_dir","'.$CS_IDS.'"',$str);
                }elseif($CS_SID==2){ //会员主页
	             $str=preg_replace('/"Skins_home_dir","(.*?)"/','"Skins_home_dir","'.$CS_IDS.'"',$str);
                }elseif($CS_SID==3){ //会员中心
	             $str=preg_replace('/"Skins_user_dir","(.*?)"/','"Skins_user_dir","'.$CS_IDS.'"',$str);
                }

                if(is_dir("./skins/".$CS_IDS)){
                     //写文件
                     write_file('./csdj/lib/Cs_Config.php', $str);
                }
            }
            $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，操作成功！</font>',site_url('admin/skins/'),'ok');
	}

	public function addsave()
	{
            $this->CsdjAdmin->Admin_Qx('38');
 	    $data['CS_SID'] = $this->input->post('CS_SID');
 	    $data['CS_Name'] = $this->input->post('CS_Name');
 	    $data['CS_TempPath'] = $this->input->post('CS_TempPath');
            if(empty($data['CS_Name']) || empty($data['CS_TempPath'])) $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，模板名称、模板路径不能为空！</font>','javascript:history.back();');

            if(substr($data['CS_TempPath'],0,5)!='user/' && $data['CS_SID']==3){
                 $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，会员中心模板必须以 user/ 开头！</font>','javascript:history.back();');
            }
            if(substr($data['CS_TempPath'],0,5)!='home/' && $data['CS_SID']==2){
                 $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，会员主页模板必须以 home/ 开头！</font>','javascript:history.back();');
            }
            if(substr($data['CS_TempPath'],0,6)!='index/' && $data['CS_SID']==1){
                 $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，主站模板必须以 index/ 开头！</font>','javascript:history.back();');
            }

            if(substr($data['CS_TempPath'],-1)!='/') $data['CS_TempPath']=$data['CS_TempPath']."/";

            if(!is_dir('./skins/'.$data['CS_TempPath'])){
                  $this->CsdjAdmin->Admin_Url('<font color=red>该模板文件不存在！</font>','javascript:history.back();');
            }

            $sql="SELECT * FROM ".CS_SqlPrefix."skins where CS_TempPath='".$data['CS_TempPath']."'";
	    $row=$this->CsdjDB->get_all($sql); 
	    if($row){
                $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，该模板已经存在！</font>','javascript:history.back();');
            }

            $this->CsdjDB->get_insert('skins',$data);
            $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，新增成功！</font>',site_url('admin/skins/'),'ok');
	}

	public function save()
	{
            $this->CsdjAdmin->Admin_Qx('38');
 	    $path = $this->input->post('path');
 	    $CS_Name = $this->input->post('CS_Name');
 	    $CS_Neir = $this->input->post('CS_Neir');
 	    $CS_Mx = $this->input->post('CS_Mx');
            if(!preg_match("/^[a-z | 0-9 | A-Z| \-\_\/]+$/",$CS_Name)) $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，文件名非法！</font>','javascript:history.back();');

            if(empty($path)){  //新增
                if(empty($CS_Name)) $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，文件名不能为空！</font>','javascript:history.back();');
                if($CS_Mx=='index'){ //主站
                      $path="./skins/".Skins_dir.$CS_Name.".html";
                }elseif($CS_Mx=='home'){ //会员主页
                      $path="./skins/".Skins_home_dir.$CS_Name.".html";
                }elseif($CS_Mx=='user'){ //会员中心
                      $path="./skins/".Skins_user_dir.$CS_Name.".html";
                }
            }

		    //获得文件扩展名
	        $file_ext = strtolower(trim(substr(strrchr($path, '.'), 1)));
			if($file_ext!='html') $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，文件名非法！</font>','javascript:history.back();');

                $fhpath=substr(str_replace($CS_Name.'.html','',$path),1);
                //写文件
                if (!write_file($path, $CS_Neir)){
                          $this->CsdjAdmin->Admin_Url('<font color=red>操作失败，文件'.$path.'没有写入权限！</font>','javascript:history.back();');
                }else{
                          $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，操作成功！</font>',site_url('admin/skins/lists/').'?path='.$fhpath,'ok');
                }
	}

	public function copy()
	{
            $this->CsdjAdmin->Admin_Qx('38');
 	    $path = $this->input->get('path');
            if(empty($path) || substr($path,0,6)!='/skins') $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，路径错误！</font>','javascript:history.back();');
  	    $path = ".".$path;
            $xpath=str_replace('.html','-复制.html',$path);

	       if(copy($path,$xpath)){
                      $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，复制成功！</font>',$_SERVER['HTTP_REFERER'],'ok');
               }else{
                      $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，复制失败！</font>','javascript:history.back();');
	       }
	}

	public function del()
	{
            $this->CsdjAdmin->Admin_Qx('38');
 	    $path = $this->input->get('path');
            if(empty($path)) $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，路径错误！</font>','javascript:history.back();');
            if(substr($path,0,6)!='/skins') $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，路径错误！</font>','javascript:history.back();');
  	    $path = ".".$path;

	         if(file_exists($path)){
		     if(!unlink($path)){
                          $this->CsdjAdmin->Admin_Url('<font color=#ff0000>抱歉，删除失败！</font>','javascript:history.back();');
                     }else{
                          $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，删除成功！</font>',$_SERVER['HTTP_REFERER'],'ok');
                     }
	         }
	}

	public function delall()
	{
            $this->CsdjAdmin->Admin_Qx('38');
            $files=$this->input->post('files');

            foreach ($files as $value) {  //文件
               if(substr($path,0,6)!='/skins'){
	            if(file_exists($value)){
		         @unlink($value);
	            }
               }
            }
            $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，删除成功！</font>',$_SERVER['HTTP_REFERER'],'ok');
	}
    //数组实列化
	public function cs_base64_encode($data) {
            $data = $data ? addslashes(serialize($data)) : '';
            $data = base64_encode($data);
            $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
            return $data;
    }
}

