<?php
class accountAction extends baseAction {
    public function index(){
    // echo convert_html_to_swf("http://v.youku.com/v_show/id_XMTU3NzMzNzE1Mg==.html?f=27282771&from=y1.3-idx-beta-1519-23042.223465.1-1");
    /*$Data = D('content_content');
    $news_list = $Data->field('id,title')->where("cid = '4'")->order("id desc")->limit(6)->select();// 首页网站公告
    $this->assign('news_list',$news_list);

    $evebts_list = $Data->field('id,title,thumb,description')->where("cid = '12'")->order("id desc")->limit(6)->select();//首页热门活动
    $this->assign('evebts_list',$evebts_list);
	$this->display(C('default_tpl').'/account/index');*/
    }
    public function login_check(){
    if(IS_POST){
            $username = $this->_post("username");
            if(preg_match( "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i", $username )){
                $where = " email = '$username' ";
            }else{
                $where = " username = '$username' ";
            }
            $password = substr(md5($this->_post("password")),8,16);
            $result = M("users")->where($where)->find();
            $pass = md5($password.$result['salt']);
            if(empty($result)){
                $this->ajaxReturn("","没有这个账号","-1");
            }else{
                if($pass == $result['password']){
                    cookie('username',$username,array('expire'=>C('logint'),'prefix'=>C('cookie_t_home')));
                    M('users_token')->where("username = '$username'")->delete();
                    $insert_data['username'] = $username;
                    $insert_data['token'] = md5(md5($username).md5($result['salt']));
                    $insert_data['logintime'] = time();
                    $g = M('users_token')->add($insert_data);
                    if($g) {
                        $this->ajaxReturn("","登录成功","1");
                    }else{
                        $this->ajaxReturn("","登录失败","-2");
                    }
                }else{
                    $this->ajaxReturn("","密码错误","-3");
                }
            }
        }else{
            echo false;//参数错误
        }
    }
    public function reg_check(){
    if(IS_POST){
            if(strlen(I('username')) < 3 || strlen(I('username')) > 18){
                // echo '用户名必须在3-18位字符之间';
                $this->ajaxReturn("","用户名必须在3-18位字符之间","-1");
                exit;
            }
            if(!preg_match( "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i", I('email'))){
                // echo '邮箱格式不正确';
                $this->ajaxReturn("","邮箱格式不正确","-2");
                exit;
            }
            if(strlen(I('password')) < 6 || strlen(I('password')) > 16){
                // echo '密码必须在6-16位字符之间';
                $this->ajaxReturn("","密码必须在6-16位字符之间","-3");
                exit;
            }
            if(I('password') != I('confirm_password')){
                // echo '两次输入密码不一致';
                $this->ajaxReturn("","两次输入密码不一致","-4");
                exit;
            }
            $users = M('users')->where("username='". I('username') ."' or email='". I('email') ."'")->find();
            if($users['username'] == I('username')){
                // echo '用户名重复';
                $this->ajaxReturn("","用户名重复","-5");
                exit;
            }
            if($users['email'] == I('email')){
                // echo '邮箱重复';
                $this->ajaxReturn("","邮箱重复","-6");
                exit;
            }
            $insert_data['username'] = I('username');
            $insert_data['email'] = I('email');
            $insert_data['salt'] = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
            $password = substr(md5(I("password")),8,16);
            $insert_data['password'] = md5($password.$insert_data['salt']);
            $insert_data['last_ip'] = get_client_ip();
            $insert_data['last_time'] = time();
            $insert_data['addtime'] = time();
            $insert_data['status'] = 1;
            $insert_data['email_check'] = 0;
            if(M("users")->add($insert_data)){
                cookie('username',I('username'),array('expire'=>C('logint'),'prefix'=>C('cookie_t_home')));
                M('users_token')->where("username = '". I('username') ."'")->delete();
                $inserts_data['username'] = I('username');
                $inserts_data['token'] = md5(md5(I('username')).md5($insert_data['salt']));
                $inserts_data['logintime'] = time();
                $g = M('users_token')->add($inserts_data);
                // echo '注册成功';
                $this->ajaxReturn("","注册成功","1");
                exit;
            }
        }else{
            echo false;//参数错误
        }
    }
    public function add(){
        $user = $this->user_info();
        $tags = M('tag')->order("number desc,id desc")->limit(20)->select();
        $this->assign('model','add');
        $this->assign('tags',$tags);
        $this->display(C('default_tpl').'/Index/add');
    }
    public function add_insert(){
        // print_r($_POST);exit;
        if(IS_POST){
            if(!I('readme')){
                $this->error('未同意发布条款');exit;
            }
            $data = M('content_content');
            $content = str_replace("\n","<br/>",$_POST['content']);
            $content = _safe($content);
            // $content = str_replace(" ","&nbsp;",$content);//以上为正则替换基本内容
            $insert_data['title'] = I('title');
            if(I('type') == '1') {
            $insert_data['content'] = $content;
            $insert_data['type'] = I('type');
            $insert_data['thumb'] = I('thumb');
            if(I('title') == ''){
                $this->error('请填写一个标题');
                exit;
            }
            if(I('content') == ''){
                $this->error('内容不能为空哦');
                exit;
            }
            }else{
            if(I('title') == ''){
                $this->error('请填写一个标题');
                exit;
            }
            if(I('url') == ''){
                $this->error('flash地址不能为空哦');
                exit;
            }
            if(convert_html_to_swf(I('url')) == false){
                $this->error('视频地址不正确,目前仅支持优酷、土豆、腾讯');
                exit;
            }
            $insert_data['video'] = convert_html_to_swf(I('url'));
            }
            $insert_data['addtime'] = time();
            $insert_data['view'] = 1;
            $insert_data['type'] = I('type');
            $insert_data['status'] = 0;//已审核
            $user = $this->user_info();
            $insert_data['author'] = $user['username'];
            $insert_data['authorid'] = $user['id'];
            $insert_data['comment_status'] = I('comment_status');
            $insert_data['anonymous'] = !$user['id']?1:0;
            if($cid = $data->data($insert_data)->add()){
                if(I('tag')){
                $taglist = explode(',',I('tag'));
                foreach($taglist as $k=>$v){
                    if($k < 3){
                    $tags = M('tag')->where("title='". $v ."'")->find();
                    if($tags) {
                        M('tag')->where("title='". $v ."'")->save(array('number'=>$tags['number']+1));
                        $tid=$tags['id'];
                    }else{
                        $tid = M('tag')->data(array('title'=>$v,'addtime'=>time(),'number'=>1))->add();
                    }
                    M('content_tag')->data(array('tid'=>$tid,'cid'=>$cid))->add();
                    }
                }
                }
                $this->success('添加成功,等待审核！');
            }else{
                $this->error('添加失败');
            }
        }else{
            $this->error("访问错误");
        }
    }
    public function update_password(){
        $user = $this->user_info();
        if($user['id']){
            $old_password = I('old_password');
            $new_password = I('new_password');
            $password_confirmation = I('password_confirmation');
            if(!$new_password || !$password_confirmation || $new_password != $password_confirmation){
                // echo '新密码设置为空或者不一致！';
                $this->ajaxReturn("","新密码设置为空或者不一致！","-1");
            }else{
                $password = substr(md5($old_password),8,16);
                $pass = md5($password.$user['salt']);
                if($pass != $user['password']){
                    // echo '当前密码错误';
                    $this->ajaxReturn("","当前密码错误","-2");
                }else{
                    //原始密码正确
                    $n_password = substr(md5($new_password),8,16);
                    $n_pass = md5($n_password.$user['salt']);
                    if(M('users')->where("id='". $user['id'] ."'")->save(array('password'=>$n_pass))){
                        // echo '修改成功';
                        $this->ajaxReturn("","修改成功","1");
                    }else{
                        // echo '修改失败';
                        $this->ajaxReturn("","修改失败","-3");
                    }
                }
            }
        }else{
            // echo '未登录';
            $this->ajaxReturn("","当前未登录","-4");
        }
    }
    public function logout(){
        $user = $this->user_info();
        cookie('feimao_xiaohua_username',null);
        M("users_token")->where("username='". $user['username'] ."'")->delete();
        $jump = gurl('','index');
        $this->success('退出成功',''.$jump.'');
    }
    public function update_authpic(){
        $user = $this->user_info();
        if($user['id']){
            if($_FILES['authpic']['error'] == '0') {
                $data_up = D('Upload');
                $info = $data_up->up();
                $update_data['authpic'] = $info[0]['savepath'].$info[0]['savename'];
                if(M("users")->where("id='".$user['id']."'")->save($update_data)){
                    $this->success("修改成功");
                }else{
                    $this->error("很抱歉 修改失败");
                }
            }else{
                $this->error("头像上传失败");
            }
        }else{
            $this->error("您还没登录哦");
        }
    }
	//登录地址
	public function qq_login($type = 'QQ'){
		empty($type) && $this->error('参数错误');

		//加载ThinkOauth类并实例化一个对象
		import("@.ORG.ThinkSDK.ThinkOauth");
		$sns  = ThinkOauth::getInstance($type);

		//跳转到授权页面
		redirect($sns->getRequestCodeURL());
	}

	//授权回调地址
	public function qq_callback($type = null, $code = null){
		(empty($type) || empty($code)) && $this->error('参数错误');
		
		//加载ThinkOauth类并实例化一个对象
		import("@.ORG.ThinkSDK.ThinkOauth");
		$sns  = ThinkOauth::getInstance($type);

		//腾讯微博需传递的额外参数
		$extend = null;
		if($type == 'tencent'){
			$extend = array('openid' => $this->_get('openid'), 'openkey' => $this->_get('openkey'));
		}

		//请妥善保管这里获取到的Token信息，方便以后API调用
		//调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
		//如： $qq = ThinkOauth::getInstance('qq', $token);
		$token = $sns->getAccessToken($code , $extend);

		//获取当前登录用户信息
		if(is_array($token)){
			$user_info = A('Type', 'Event')->$type($token);
			$users_info = M('users')->where("openid='". $token['openid'] ."'")->find();
			if($users_info) {
				cookie('username',$users_info['username'],array('expire'=>C('logint'),'prefix'=>C('cookie_t_home')));
				M('users_token')->where("username = '". $users_info['username'] ."'")->delete();
				$inserts_data['username'] = $users_info['username'];
				$inserts_data['token'] = md5(md5($users_info['username']).md5($users_info['salt']));
				$inserts_data['logintime'] = time();
				$g = M('users_token')->add($inserts_data);
				// echo '注册成功';
				header("Location:". __ROOT__ ."/");
				exit;
			}else{
				$insert_data['username'] = $user_info['nickname'];
				$insert_data['openid'] = $token['openid'];
				//$insert_data['authpic'] = GrabImage($user_info['figureurl_qq_2'], "");
				$insert_data['salt'] = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
				$password = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
				$password = substr(md5($password),8,16);
				$insert_data['password'] = md5($password.$insert_data['salt']);
				$insert_data['last_ip'] = get_client_ip();
				$insert_data['last_time'] = time();
				$insert_data['addtime'] = time();
				$insert_data['status'] = 1;
				$insert_data['email_check'] = 0;
				if(M("users")->add($insert_data)){
					cookie('username',$insert_data['username'],array('expire'=>C('logint'),'prefix'=>C('cookie_t_home')));
					M('users_token')->where("username = '". $insert_data['username'] ."'")->delete();
					$inserts_data['username'] = $insert_data['username'];
					$inserts_data['token'] = md5(md5($insert_data['username']).md5($insert_data['salt']));
					$inserts_data['logintime'] = time();
					$g = M('users_token')->add($inserts_data);
					// echo '注册成功';
					header("Location:". __ROOT__ ."/");
					exit;
				}else{
					$this->error('登录失败',__ROOT__.'/');
				}
			}
		}else{
			$this->error('登录失败',__ROOT__.'/');
		}
	}
    public function uploadfile() {
        $file_path = __ROOT__. 'uploads/images/'.date('Ymd',time()).'/';
        if(!is_dir($file_path)) {
            mkdir($file_path,0777,true);
        }

        if (!empty($_FILES)) {
            $url = $this->_upload($file_path);
            $this->ajaxReturn(array('status' => 1,'info' => '上传成功','url' => $url['image'], 'm_url' => $url['m_image']));
        }
    }
    private function _upload($savePath,$is_thumb = true) {
        $fileParts = pathinfo($_FILES['Filedata']['name']);
        $extension = $fileParts['extension'];

        import("ORG.Net.UploadFile"); 
        //导入上传类 
        $upload = new UploadFile(); 
        //设置上传文件大小 
        $upload->maxSize = 5120 * 5120; 
        //设置上传文件类型 
        $upload->allowExts = explode(',', 'jpg,gif,png,jpeg'); 
        //设置附件上传目录 
        $upload->savePath = $savePath; 
        if($is_thumb) {
            //1 按设置大小截取 0 按原图等比例缩略
            $upload->thumbType = 0;
            //设置需要生成缩略图，仅对图像文件有效 
            $upload->thumb = true; 
            // 设置引用图片类库包路径 
            $upload->imageClassPath = 'ORG.Util.Image'; 
            //设置需要生成缩略图的文件后缀 
            $upload->thumbPrefix = 'm_';  //生产2张缩略图 
            //设置缩略图最大宽度 
            $upload->thumbMaxWidth = '540'; 
            //设置缩略图最大高度 
            $upload->thumbMaxHeight = '10000'; 

            if($extension != 'gif' && $extension != 'GIF') {
                //删除原图 
                $upload->thumbRemoveOrigin = true; 
            }
        }
        //设置上传文件规则 
        $upload->saveRule = uniqid; 
       
        if (!$upload->upload()) { 
            //捕获上传异常 
            $this->error($upload->getErrorMsg()); 
        } else { 
            //取得成功上传的文件信息 
            $uploadList = $upload->getUploadFileInfo(); 
            import("ORG.Util.Image");
            
            $image = $uploadList[0]['savepath'] . $uploadList[0]['savename']; 
            //缩略图路径
            if($is_thumb) {
                $m_image = $uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename']; 
                
                if($extension != 'gif' && $extension != 'GIF') {
                    //给m_缩略图添加水印, Image::water('原文件名','水印图片地址') 
                    Image::water($m_image, $this->setting['site_short_domain']); 
                    $image = $m_image;
                }
            }
        } 
        return array('image' => $image, 'm_image' => $m_image);
    } 
}