<?php
class PublicAction extends Action {
	
	public function _initialize() {
	   
		//文章分类显示
		$Cate = M("Category");
		//$cateList = $Cate->findAll();
		//$cateList = list_to_tree(); 
        $cateList=$Cate->field("id,title,pid,path,concat(path,'-',id) as bpath")->order('bpath')->select();
	    foreach($cateList as $key=>$value){
				$cateList[$key]['count']=count(explode('-',$value['bpath']));
			}
		$HeaderCateList=$Cate->where('pid=0')->order('id')->select();
		$this->assign("category", $cateList);
		$this->assign("headercategory", $HeaderCateList);
		
		//产品分类显示
         $Cate = M("Procategory");
		 $cateList=$Cate->field("id,title,pid,path,concat(path,'-',id) as bpath")->order('bpath')->select();
	      foreach($cateList as $key=>$value){
				  $cateList[$key]['count']=count(explode('-',$value['bpath']));
			      }
		  $this->assign("procategory", $cateList);
		  
		 // 关于我们    
        $Aboutus = M("Aboutus", "AdvModel");
         // 需要将msubstr()从扩展库extend.php中拷贝到common.php中
        $new = $Aboutus->order("displayId desc")->top6();
        $this->assign("lastAboutus", $new);
        //公司文章
        $Article = M("Article", "AdvModel");
         // 需要将msubstr()从扩展库extend.php中拷贝到common.php中
        $new = $Article->where('status=1')->order("cTime desc")->top6();
        $this->assign("lastArticles", $new);
           // 友情链接    
        $Links = M("Links", "AdvModel");
         // 需要将msubstr()从扩展库extend.php中拷贝到common.php中
        $new = $Links->where('status=1')->order("id desc")->top6();
        $this->assign("lastLinks", $new);
            // 公司产品           
        $Product = M("Product", "AdvModel");                 
        // 需要将msubstr()从扩展库extend.php中拷贝到common.php中
        $new = $Product->where('status=1')->order("cTime desc")->top6();               
        $this->assign("lastProducts", $new);
    
	}

    public function getAttach() {
        //读取附件信息
	    $id = $_GET['id'];
        $dao = M('Attach');
        $attachs = $dao->where("module=".MODULE_NAME)->where("recordId=".$id)->select();
		//模板变量赋值
		$this->assign("attachs",$attachs?$attachs:'');

	}
    public function download()
    {
        import("@.ORG.Http");
        $id         =   $_GET['id'];
        $dao        =   M("Attach");
        $attach	    =   $dao->where("id=".$id)->find();
        $filename   =   $attach["savepath"].$attach["savename"];
        if(is_file($filename)) {
			if(!isset($_SESSION['attach_down_count_'.$id])) {
				$dao->setInc('downCount',"id=".$id);
				$_SESSION['attach_down_count_'.$id]	= true;
			}
            Http::download($filename,auto_charset($attach->name,'utf-8','gbk'));
        }
    }
   public function down()
    {
        import("@.ORG.Http");
        $id         =   $_GET['id'];
        $dao        =   M("Down");
        $down	    =   $dao->where("id=".$id)->find();
        $filename   =   $down["savepath"].$down["attachment"];
        if(is_file($filename)) {
			if(!isset($_SESSION['down_down_count_'.$id])) {
				$dao->setInc('downCount',"id=".$id);
				$_SESSION['down_down_count_'.$id]	= true;
			}
            Http::download($filename,auto_charset($down->title,'utf-8','gbk'));
        }
    }
    
       /**
     +----------------------------------------------------------
     * 文件上传功能，支持多文件上传、保存数据库、自动缩略图
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param string $module 附件保存的模块名称
     * @param integer $id 附件保存的模块记录号
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function _upload($module='',$recordId='')
    {
        import("@.ORG.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize  = 32922000 ;
        //设置上传文件类型
        $upload->allowExts  = array('rar','zip','doc','swf','txt','ppt','jpg','gif');
        $upload->savePath =  './Public/Uploads/';
        if(isset($_POST['_uploadSaveRule'])) {
            //设置附件命名规则
            $upload->saveRule =  $_POST['_uploadSaveRule'];
        }else{
              $upload->saveRule = 'uniqid';
        }
        if(!empty($_POST['_uploadFileTable'])) {
            //设置附件关联数据表
            $module =  $_POST['_uploadFileTable'];
        }
        if(!empty($_POST['_uploadRecordId'])) {
            //设置附件关联记录ID
            $recordId =  $_POST['_uploadRecordId'];
        }
        if(!empty($_POST['_uploadFileId'])) {
            //设置附件记录ID
            $id =  $_POST['_uploadFileId'];
        }
        if(!empty($_POST['_uploadFileVerify'])) {
            //设置附件验证码
            $verify =  $_POST['_uploadFileVerify'];
        }
        if(!empty($_POST['_uploadUserId'])) {
            //设置附件上传用户ID
            $userId =  $_POST['_uploadUserId'];
        }else {
        	$userId = isset($_SESSION[C('USER_AUTH_KEY')])?$_SESSION[C('USER_AUTH_KEY')]:0;
        }
        if(!empty($_POST['_uploadImgThumb'])) {
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb =  $_POST['_uploadImgThumb'];
            $upload->imageClassPath = '@.ORG.Image';
        }
        if(!empty($_POST['_uploadThumbSuffix'])) {
            //设置需要生成缩略图的文件后缀
            $upload->thumbSuffix =  $_POST['_uploadThumbSuffix'];
        }
        if(!empty($_POST['_uploadThumbMaxWidth'])) {
            //设置缩略图最大宽度
            $upload->thumbMaxWidth =  $_POST['_uploadThumbMaxWidth'];
        }
        if(!empty($_POST['_uploadThumbMaxHeight'])) {
            //设置缩略图最大高度
            $upload->thumbMaxHeight =  $_POST['_uploadThumbMaxHeight'];
        }
		// 支持图片压缩文件上传后解压
	if(!empty($_POST['_uploadZipImages'])) {
		$upload->zipImages = true;
	}
        $uploadReplace =  false;
        if(isset($_POST['_uploadReplace']) && 1==$_POST['_uploadReplace']) {
            //设置附件是否覆盖
            $upload->uploadReplace =  true;
            $uploadReplace = true;
        }
            $uploadFileVersion = false;
        if(isset($_POST['_uploadFileVersion']) && 1==$_POST['_uploadFileVersion']) {
            //设置是否记录附件版本
            $uploadFileVersion =  true;
        }
        $uploadRecord  =  true;
        if(isset($_POST['_uploadRecord']) && 0==$_POST['_uploadRecord']) {
            //设置附件数据是否保存到数据库
            $uploadRecord =  false;
        }
        // 记录上传成功ID
        $uploadId =  array();
        $savename = array();
        //执行上传操作
        if(!$upload->upload()) {
            if($this->isAjax() && isset($_POST['_uploadFileResult'])) {
                $uploadSuccess =  false;
                $ajaxMsg  =  $upload->getErrorMsg();
            }else {
                //捕获上传异常
                $this->error($upload->getErrorMsg());
            }
        }else {
            if($uploadRecord) {
            	// 附件数据需要保存到数据库
                 //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
				$remark = $_POST['remark'];
                //保存附件信息到数据库
                $Attach = M('Attach');
                //启动事务
                //$Attach->startTrans();
                foreach($uploadList as $key=>$file) {
                    //记录模块信息
                    $file['module']     =   $module;
                    $file['recordId']   =   $recordId?$recordId:0;
                    $file['userId']     =   $userId;
                    $file['verify']	=   $verify?$verify:'';
                    $file['remark']	=   $remark[$key]?$remark[$key]:($remark?$remark:'');
                    //保存附件信息到数据库
                    if($uploadReplace ) {
			if(!empty($id)) {
	                        $vo  =  $Attach->where("id=".$id)->find();
			}else{
	                        $map["module"] = $mobule;
                                $map["recordId"] = $recordId;
                                $vo  =  $Attach->where($map)->select();
			}
			if(is_object($vo)) {
				$vo	=	get_object_vars($vo);
			}
                        if(false !== $vo) {
                            // 如果附件为覆盖方式 且已经存在记录，则进行替换
                            $id = $vo[$Attach->getPk()];
							if($uploadFileVersion) {
								// 记录版本号
								$file['version']	 =	 $vo['version']+1;
								// 备份旧版本文件
								$oldfile	=	$vo['savepath'].$vo['savename'];
								if(is_file($oldfile)) {
									if(!file_exists(dirname($oldfile).'/_version/')) {
										mkdir(dirname($oldfile).'/_version/');
									}
									$bakfile	=	dirname($oldfile).'/_version/'.$id.'_'.$vo['version'].'_'.$vo['savename'];
									$result = rename($oldfile,$bakfile);
								}
							}
							// 覆盖模式
							$file['updateTime']	=	time();
							$Attach->save($file,"id='".$id."'");
							$uploadId[]   = $id;

                        }else {
			    $file['uploadTime'] =   time();
                            $uploadId[] = $Attach->add($file);
                        }
                    }else {
                        //保存附件信息到数据库
		        $file['uploadTime'] =   time();
                        $uploadId[] =  $Attach->add($file);
                    }
                    $savename[] =  $file['savename'];
                }
                //提交事务
                //$Attach->commit();
            }
            $uploadSuccess =  true;
            $ajaxMsg  =  '';
        }

        // 判断是否有Ajax方式上传附件
        // 并且设置了结果显示Html元素
        if($this->isAjax() && isset($_POST['_uploadFileResult']) ) {
            // Ajax方式上传参数信息
            $info = Array();
            $info['success']  = $uploadSuccess;
            $info['message']  = $ajaxMsg;
            //设置Ajax上传返回元素Id
            $info['uploadResult'] =  $_POST['_uploadFileResult'];
            if(isset($_POST['_uploadFormId'])) {
                //设置Ajax上传表单Id
                $info['uploadFormId'] =  $_POST['_uploadFormId'];
            }
            if(isset($_POST['_uploadResponse'])) {
                //设置Ajax上传响应方法名称
                $info['uploadResponse'] =  $_POST['_uploadResponse'];
            }
            if(!empty($uploadId)) {
                $info['uploadId'] = implode(',',$uploadId);
            }
            $info['savename']   = implode(',',$savename);
            $this->ajaxUploadResult($info);
        }
        return ;

    }

    /**
     +----------------------------------------------------------
     * Ajax上传页面返回信息
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param array $info 附件信息
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function ajaxUploadResult($info)
    {
        // Ajax方式附件上传提示信息设置
        // 默认使用mootools opacity效果
        //alert($info);
        $show   = '<script language="JavaScript" src="'.WEB_PUBLIC_PATH.'/Js/mootools.js"></script><script language="JavaScript" type="text/javascript">'."\n";
        $show  .= ' var parDoc = window.parent.document;';
        $show  .= ' var result = parDoc.getElementById("'.$info['uploadResult'].'");';
        if(isset($info['uploadFormId'])) {
   	        $show  .= ' parDoc.getElementById("'.$info['uploadFormId'].'").reset();';
        }
        $show  .= ' result.style.display = "block";';
        $show .= " var myFx = new Fx.Style(result, 'opacity',{duration:600}).custom(0.1,1);";
        if($info['success']) {
            // 提示上传成功
            $show .=  'result.innerHTML = "<div style=\"color:#3333FF\"> 文件上传成功！</div>";';
            // 如果定义了成功响应方法，执行客户端方法
            // 参数为上传的附件id，多个以逗号分割
            if(isset($info['uploadResponse'])) {
                $show  .= 'window.parent.'.$info['uploadResponse'].'("'.$info['uploadId'].'","'.$info['savename'].'");';
            }
        }else {
            // 上传失败
            // 提示上传失败
            $show .=  'result.innerHTML = "<div style=\"color:#FF0000\"> 上传失败：'.$info['message'].'</div>";';
        }
        $show .= "\n".'</script>';
        //$this->assign('_ajax_upload_',$show);
        header("Content-Type:text/html; charset=utf-8");

        exit($show);
        return ;
   	}

        public function upload() {
            if(!empty($_FILES)) {//如果有文件上传
			// 上传附件并保存信息到数据库
			$this->_upload(MODULE_NAME);
            }
	}

    public function comment() {
    	if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->assign('jumpUrl',__APP__.'/Public/login');
			$this->error('没有登录');
		}else{
        $Comment = D('Comment');
        if ($comment = $Comment->create()) {
            //dump($comment);
            $list = $Comment->add();
            if ($list) {
                // 更新评论数
		$objDao = D("Blog");
		$objDao->setInc('commentCount',"id='".$comment["recordId"]."'");
		// 返回客户端数据
                $comment["content"] = nl2br(ubb(trim($comment["content"])));
                $comment["id"] = $list;
                $this->ajaxReturn($comment,"评论成功！",1);
            }else {
                $this->error("评论失败!");
            }
        }else {
            $this->error($Comment->getError());
        }
	  }
    }

    public function getComment() {
        $id = $_REQUEST["id"];
        $CommList = D("Comment");

        //导入分页类
        import("@.ORG.Page");
        //取得满足条件的记录数
        $count = $CommList->where('recordId='.$id)->count();
        $p = new Page($count,5);
        $p->setConfig('header' ,'条评论');
        //分页查询数据
        $comments = $CommList->where('recordId='.$id)->order("cTime")->limit($p->firstRow.','.$p->listRows)->select();
        //模板变量赋值
        $this->assign("comments",$comments);
	$page  = $p->show();
	$this->assign("page",$page);
    }

    

    public function verify()
    {
	$type = isset($_GET['type'])?$_GET['type']:'gif';
        import("@.ORG.Image");
        Image::buildImageVerify(4,1,$type);
    }



	// 检查用户是否登录

	protected function checkUser() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->assign('jumpUrl','Public/login');
			$this->error('没有登录');
		}
	}

	// 顶部页面
	public function top() {
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$model	=	M("Category");
		$list	=	$model->where('pid=0')->getField('id,title');
		$this->assign('CategoryList',$list);
		$this->display();
	}
	// 尾部页面
	public function footer() {
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
	
		$this->display();
	}
	// 菜单页面
	public function menu() {
        $this->checkUser();
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
            //显示菜单项
            $menu  = array();
            if(isset($_SESSION['menu'.$_SESSION[C('USER_AUTH_KEY')]])) {

                //如果已经缓存，直接读取缓存
                $menu   =   $_SESSION['menu'.$_SESSION[C('USER_AUTH_KEY')]];
            }else {
                //读取数据库模块列表生成菜单项
                $category    =   M("Category");
				$id	=	$category->getField("id");

				$where['pid']=$id;
                $list	=	$category->where($where)->field("id,title,category_id,pid")->order('id')->select();
                $accessList = $_SESSION['_ACCESS_LIST'];
                foreach($list as $key=>$module) {
                     if(isset($accessList[strtoupper(APP_NAME)][strtoupper($module['title'])])) {
                        //设置模块访问权限
                        $module['access'] =   1;
                        $menu[$key]  = $module;
                    }
                }
                //缓存菜单访问
                $_SESSION['menu'.$_SESSION[C('USER_AUTH_KEY')]]	=	$menu;
            }
            if(!empty($_GET['tag'])){
                $this->assign('menuTag',$_GET['tag']);
            }
			//dump($menu);
            $this->assign('menu',$menu);
		}
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$this->display();
	}

    // 用户首页 查看信息

        public function main() {          
        $this->checkUser();
		$User	 =	 M("User");
		$vo	=	$User->getById($_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('vo',$vo);
		$this->display();
        }
	// 用户登录页面
	public function login() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->display();
		}else{
			$this->redirect('User/index');
		}
	}


	// 用户登出
    public function logout()
    {
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
			unset($_SESSION[C('USER_AUTH_KEY')]);
			unset($_SESSION);
			session_destroy();
            $this->assign("jumpUrl",__URL__.'/login/');
            $this->success('登出成功！');
        }else {
            $this->error('已经登出！');
        }
    }

	// 登录检测
	public function checkLogin() {
		if(empty($_POST['account'])) {
			$this->error('帐号错误！');
		}elseif (empty($_POST['password'])){
			$this->error('密码必须！');
		}
        //生成认证条件
        $map            =   array();
		// 支持使用绑定帐号登录
		$map['account']	= $_POST['account'];
        $map["status"]	=	array('gt',0);
		
		import ( '@.ORG.RBAC' );
        $authInfo = RBAC::authenticate($map);
        //使用用户名、密码和状态的方式进行认证
        if(false === $authInfo) {
            $this->error('帐号不存在或已禁用！');
        }else {
            if($authInfo['password'] != md5($_POST['password'])) {
            	$this->error('密码错误！');
            }
            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
            $_SESSION['email']	=	$authInfo['email'];
            $_SESSION['loginUserName']		=	$authInfo['nickname'];
            $_SESSION['lastLoginTime']		=	$authInfo['last_login_time'];
			$_SESSION['login_count']	=	$authInfo['login_count'];
            if($authInfo['account']=='admin') {
            	$_SESSION['administrator']		=	true;
            }
            //保存登录信息
			$User	=	M('User');
			$ip		=	get_client_ip();
			$time	=	time();
            $data = array();
			$data['id']	=	$authInfo['id'];
			$data['last_login_time']	=	$time;
			$data['login_count']	=	array('exp','login_count+1');
			$data['last_login_ip']	=	$ip;
			$User->save($data);

			// 缓存访问权限
            RBAC::saveAccessList();
			$this->success('登录成功！');

		}
	}
    // 更换密码
    public function changePwd()
    {
		$this->checkUser();
        //对表单提交处理进行处理或者增加非表单数据
		if(md5($_POST['verify'])	!= $_SESSION['verify']) {
			$this->error('验证码错误！');
		}
		$map	=	array();
        $map['password']= pwdHash($_POST['oldpassword']);
        if(isset($_POST['account'])) {
            $map['account']	 =	 $_POST['account'];
        }elseif(isset($_SESSION[C('USER_AUTH_KEY')])) {
            $map['id']		=	$_SESSION[C('USER_AUTH_KEY')];
        }
        //检查用户
        $User    =   M("User");
        if(!$User->where($map)->field('id')->find()) {
            $this->error('旧密码不符或者用户名错误！');
        }else {
			$User->password	=	pwdHash($_POST['password']);
			$User->save();
			$this->success('密码修改成功！');
         }
    }
   public function profile() {
		$this->checkUser();
		$User	 =	 M("User");
		$vo	=	$User->getById($_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('vo',$vo);
		$this->display();
	}

// 修改资料
	public function change() {
		$this->checkUser();
		$User	 =	 D("User");
		if(!$User->create()) {
			$this->error($User->getError());
		}
		$result	=	$User->save();
		if(false !== $result) {
			$this->success('资料修改成功！');
		}else{
			$this->error('资料修改失败!');
		}
	}


}
?>