<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Plugins 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()
	{
 	    $page = $this->input->get('page');
            if(empty($page)) $page=1;

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

            $data['pagesize']=40;
            $data['page']=$page;
            $data['pagejs']=ceil((count($arrs)-1) / $data['pagesize']); //总页数
            $data['url']=site_url('admin/plugins/index/')."?";
            $data['show']=array_slice($arrs,$data['pagesize']*(($page>$data['pagejs']?$data['pagejs']:$page)-1),$data['pagesize']);

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

	/**
	 * 插件配置/简介
	 */
	public function set()
	{
            $this->CsdjAdmin->Admin_Qx('46');
	    $id=$this->input->get_post('id');
            $row=$this->CsdjDB->get_select ('plugins','CS_ID','*',''.$id.'');

            if(!$row) $this->CsdjAdmin->Admin_Url('<font color=red>该插件不存在！</font>','javascript:history.back();');

            $data['description']=$row[0]->CS_Description;
            $this->load->view('admin/plugins_set',$data);

        }

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

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

	        //包含控制器的插件    
	 	$installfile   = PLUGINDIR . $dir . '/install.php';
	        if (!file_exists($installfile) || @$config['mid']=='') $this->CsdjAdmin->Admin_Url('<font color=red>插件缺少安装配置文件！</font>','javascript:history.back();');
                require_once $installfile;
	        if ($install) {
	            //数据表安装
	            if (is_array($install)) {
	                foreach ($install as $sql) {
	                    $this->CsdjDB->get_table(str_replace('{prefix}', CS_SqlPrefix, $sql));
	                }
	            } else {
	                $this->plugin->get_table(str_replace('{prefix}', CS_SqlPrefix, $install));
	            }
	        }
	       //代码调用插件，直接添加表中记录
               $updata['CS_Name']=$config['name'];
               $updata['CS_Author']=$config['author'];
               $updata['CS_Version']=$config['version'];
               $updata['CS_Description']=$config['description'];
               $updata['CS_Dir']=$dir;

               $this->CsdjDB->get_insert('plugins',$updata);
	           $app['site']=Web_Url;
               echo '<script src="'.CS_YPTURL.'/plub/installs?time='.time().'&param='.cs_base64_encode($app).'&id='.$config['mid'].'"></script>';
               $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，安装成功！</font>',$_SERVER['HTTP_REFERER'],'ok');
        }


	/**
	 * 卸载插件
	 */
	public function del()
	{
            $this->CsdjAdmin->Admin_Qx('46');
	    $id=$this->input->get_post('id');
	    $dir=$this->input->get_post('dir');
            if(empty($id) || empty($dir)) $this->CsdjAdmin->Admin_Url('<font color=red>参数错误！</font>','javascript:history.back();');

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

	        //包含控制器的插件
	 	$uninstallfile   = PLUGINDIR . $dir . '/uninstall.php';
	        if (!file_exists($uninstallfile)) $this->CsdjAdmin->Admin_Url('<font color=red>该插件卸载文件不存在！</font>','javascript:history.back();');
                require_once $uninstallfile;

	        if ($uninstall) {
	            //数据表删除
	            if (is_array($uninstall)) {
	                foreach ($uninstall as $sql) {
	                    $this->CsdjDB->get_table(str_replace('{prefix}', CS_SqlPrefix, $sql));
	                }
	            } else {
	                $this->plugin->get_table(str_replace('{prefix}', CS_SqlPrefix, $uninstall));
	            }
	        }

            $this->db->query("delete from ".CS_SqlPrefix."plugins where CS_ID in (".$id.")");
	        $app['site']=Web_Url;
            echo '<script src="'.CS_YPTURL.'/plub/uinstall?time='.time().'&param='.cs_base64_encode($app).'&id='.$config['mid'].'"></script>';
            $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，卸载成功！</font>',$_SERVER['HTTP_REFERER'],'ok');
        }

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

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

	        //包含控制器的插件
	 	$uninstallfile   = PLUGINDIR . $dir . '/uninstall.php';
	        if (!file_exists($uninstallfile)) $this->CsdjAdmin->Admin_Url('<font color=red>该插件卸载文件不存在！</font>','javascript:history.back();');
                require_once $uninstallfile;
	        if ($uninstall) {
	            //数据表删除
	            if (is_array($uninstall)) {
	                foreach ($uninstall as $sql) {
	                    $this->CsdjDB->get_table(str_replace('{prefix}', CS_SqlPrefix, $sql));
	                }
	            } else {
	                $this->plugin->get_table(str_replace('{prefix}', CS_SqlPrefix, $uninstall));
	            }
	        }

            //删除插件目录
            $this->CsdjAdmin->deldir('./plugins/'.$dir);
            $this->db->query("delete from ".CS_SqlPrefix."plugins where CS_Dir='".$dir."'");

            $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，删除成功！</font>',site_url('admin/plugins/index'),'ok');
        }


	/**
	 * 关闭/打开插件
	 */
	public function disable()
	{
            $this->CsdjAdmin->Admin_Qx('46');
	    $id=$this->input->get_post('id');
	    $sid=$this->input->get_post('sid');
            if(empty($id)) $this->CsdjAdmin->Admin_Url('<font color=red>参数错误，ID为空！</font>','javascript:history.back();');
            if($sid==0){
                  $updata['CS_SID']=1;
            }else{
                  $updata['CS_SID']=0;
            }
            $this->CsdjDB->get_update('plugins',$id,$updata);
            $this->CsdjAdmin->Admin_Url('<font color=#0000ff>恭喜您，操作成功！</font>',$_SERVER['HTTP_REFERER'],'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."?param=".$this->cs_base64_encode($app);
            header("Location: ".$plugins_api.""); 
	}

	/**
	 * 插件评分
	 */
	public function pingfen(){

	        $id=$this->input->get('id');
	        $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."plub/show/".$id."?param=".$this->cs_base64_encode($app)."#ratecomment";
            header("Location: ".$plugins_api.""); 
	}

	/**
	 * 插件下载
	 */
	public function down()
	{

            $dir=$this->input->get_post('dir');
            $mid=$this->input->get_post('mid');
            $key=$this->input->get_post('key');

	        if (empty($mid) || empty($dir)){

                  $this->CsdjAdmin->Admin_Url('抱歉，参数错误！',site_url('admin/plugins/yun'),'no');

			}else{  //下载
                  $app['data']['key']=$key;
	              $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;

                  $zip=CS_YPTURL."plub/down/".$mid."?param=".$this->cs_base64_encode($app);
                  $zippath="./attachment/other/plugins_".$dir.".zip";
                  $testzip_path="./plugins/";
                  $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/plugins/yun/'));
    	          if ($files_file=='-3') $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，目录（./attachment/other/）没有写入权限！</font>',site_url('admin/plugins/yun/'));
	              if (filesize($zippath) == 0) $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，插件下载失败！</font>',site_url('admin/plugins/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/plugins/yun/'));
		          }else{

		                  if (!file_exists($testzip_path.$dir.'/config.php') || !file_exists($testzip_path.$dir.'/install.php')) {
			                @unlink($zippath);
                            $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，插件不完整1！</font>',site_url('admin/plugins/yun/'));
						  }
			              //配置文件验证
			              if (filesize($testzip_path.$dir.'/config.php') == 0 || filesize($testzip_path.$dir.'/install.php') == 0) {
			                @unlink($zippath);
                            $this->CsdjAdmin->Admin_Url('<font color=red>抱歉，插件不完整2！</font>',site_url('admin/plugins/yun/'));
						  }
			              @unlink($zippath);
                          $this->CsdjAdmin->Admin_Url('<font color=red>恭喜您，插件下载成功！</font>',site_url('admin/plugins/index/'),'ok');
				  }

			}

	}

    //数组实列化
	public function cs_base64_encode($data) {
            $data = $data ? addslashes(serialize($data)) : '';
            $data = base64_encode($data);
            $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
            return $data;
    }
}

