LoginController.php 14.5 KB
<?php
/**
 * 登录注册
 * Author: xiaojie
 * DateTime: 2018/11/26 13:50
 */
namespace app\portal\controller;

use app\portal\model\CityCategoryModel;
use app\portal\model\UserModel;
use app\portal\validate\UsersValidate;
use cmf\controller\HomeBaseController;
use app\portal\model\CollectionModel;
use cmf\lib\Storage;
use think\Db;
use anerg\OAuth2\OAuth;
use think\Config;

class LoginController extends HomeBaseController
{
    private $limit = 8;//收藏,搜索分页
    //登录页面
    public function login(){
        return $this->fetch();
    }

    //登录提交
    public function loginCommit(){
        //提交参数手机号(mobile),密码(user_pass)
        $param = $this->request->param();
        $validate = new UsersValidate();
        $userModel = new UserModel();
        $map = [
            'mobile' => $param['mobile'],
            'user_pass' => cmf_password($param['user_pass']),
            'user_type' => 2,
            'user_status' => 1,
        ];
        $userInfo = $userModel->where($map)->find();
        if(!$userInfo){
            $this->apiResponse(0,'账号或密码错误');
        }
        $ip = get_client_ip();
        $data = [
            'id' => $userInfo['id'],
            'last_login_time' => time(),
            'last_login_ip' => $ip,
        ];

        if(!$validate->scene('edit')->check($data)){
            $this->apiResponse(0,$validate->getError());
        }
        $res = $userModel->isUpdate(true)->save($data);
        if($res){
            //用户信息存入session
            cmf_update_current_user($userInfo);
            $this->apiResponse(1,'登录成功');
        }
        $this->apiResponse(0,'未知错误');
    }

    //第三方登录页面
    public function thirdLogin(){
        return $this->fetch();
    }

    //注册页面
    public function register(){
        return $this->fetch();
    }

   //注册提交
    public function registerCommit(){
        //提交参数手机号(mobile),验证码(mobile_code),密码(user_pass)
        $param = $this->request->param();
        //验证验证码是否正确
        $common = new CommonController();
        $common->validateMobileCode($param);
        //验证场景add
        $validate = new UsersValidate();
        if(!$validate->scene('add')->check($param)){
            $this->apiResponse(0,$validate->getError());
        }
        if(empty($param['user_pass'])){
            $this->apiResponse(0,'密码不能为空!');
        }
        //是否已注册
        $userModel = new UserModel();
        $userInfo = $userModel->where(['mobile'=>$param['mobile'],'user_type'=>2])->find();
        if($userInfo){
            $this->apiResponse(0,'此账号已被注册');
        }
        //新增注册信息
        $info['mobile'] = $param['mobile'];
        $info['user_pass'] = cmf_password($param['user_pass']);
        $info['user_type'] = 2;
        $info['create_time'] = time();
        $res = $userModel->allowField(true)->save($info);
        if($res){
            $this->apiResponse(1,'注册成功');
        }
        $this->apiResponse(0,'未知错误');
    }

    //首页个人中心
    public function info(){
        return $this->fetch();
    }

    //首页个人中心修改头像
    public function updateAvatar(){
        //判断是否登录
        $login = cmf_is_user_login();
        if($login){
            $file   = $this->request->file('avatar');
            if (empty($file)) {
                $this->apiResponse(0,'未检测出文件!');
            }
            $result = $file->validate([
                'ext'  => 'jpg,jpeg,png',
                'size' => 1024 * 1024
            ])->move(WEB_ROOT . 'upload' . DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR);

            if ($result) {
                $avatarSaveName = str_replace('//', '/', str_replace('\\', '/', $result->getSaveName()));
                $avatar         = 'avatar/' . $avatarSaveName;
                $avatarPath = WEB_ROOT . "upload/" . $avatar;

                $storage = new Storage();
                $storage->upload($avatar, $avatarPath, 'image');
                $id = cmf_get_current_user_id();

                $userModel = new UserModel();
                $res = $userModel->allowField(true)->update(['id'=>$id,'avatar'=>$avatar]);
                if($res){
                    $userInfo = $userModel->where('id',$id)->find();
                    cmf_update_current_user($userInfo);
                    $this->apiResponse(1,'上传成功!');
                }else{
                    $this->apiResponse(0,'上传失败!');
                }
            } else {
                $this->apiResponse(0,$file->getError());
            }
        }else{
            $this->apiResponse(0,'请登录后修改头像!');
        }
    }

    //个人中心编辑页面
    public function editInfo(){
        return $this->fetch();
    }

    //个人中心编辑提交
    public function updateNickname(){
        //判断是否登录
        $login = cmf_is_user_login();
        $nickname = $this->request->param('nickname');
        if($login){
            $userModel = new UserModel();
            $id = cmf_get_current_user_id();
            if(empty($nickname)){
                $this->apiResponse(0,'昵称不能为空!');
            }
            $res = $userModel->allowField(true)->update(['id'=>$id,'user_nickname'=>$nickname]);
            if($res){
                $userInfo = $userModel->where('id',$id)->find();
                cmf_update_current_user($userInfo);
                $this->apiResponse(1,'保存成功!');
            }else{
                $this->apiResponse(0,'保存失败!');
            }
        }else{
            $this->apiResponse(0,'请登录后修改资料!');
        }
    }

    //我的收藏列表
    public function myCollection(){
        $limit = $this->limit;
        $uid = cmf_get_current_user_id();
//        $collectionModel = new CollectionModel();
//        $res = $collectionModel
//            ->where(['uid'=>$uid])
//            ->field('id,post_id,category_name,city_name,post_url')
//            ->order('id desc')
//            ->paginate($limit);
        $res = Db::name('collection')
            ->alias('c')
            ->join('portal_post p','c.post_id = p.id')
            ->where(['c.uid'=>$uid,'p.delete_time'=>0])
            ->field('c.id,c.category_name,c.city_name,c.post_url,p.post_title,p.post_excerpt,p.post_favorites')
            ->order('c.id desc')
            ->paginate($limit);
        $data = $res->toArray();
        $page = $res->render();
//        $post_ids = array_unique(array_column($data['data'],'post_id'));
//        $data1 = Db::name('portal_post')
//            ->whereIn('id',$post_ids)
//            ->where('delete_time', 0)
//            ->field('id,post_title,post_excerpt,post_favorites')
//            ->order('weigh desc')
//            ->select()
//            ->toArray();
//        foreach($data['data'] as &$value){
//            $value['post_title'] = '';
//            $value['post_excerpt'] = '';
//            $value['post_favorites'] = '';
//            foreach ($data1 as $item) {
//                if($value['post_id'] == $item['id']){
//                    $value['post_title'] = $item['post_title'];
//                    $value['post_excerpt'] = $item['post_excerpt'];
//                    $value['post_favorites'] = $item['post_favorites'];
//                }
//            }
//        }
        $this->assign('res',$data['data']);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //搜索列表
    public function searchList(){
        $keyword = $this->request->param('keyword');
        if(isset($keyword) && !empty($keyword)){
            $limit = $this->limit;
            $res = Db::name('portal_post')
                ->alias('p')
                ->join('city_category c','p.city_id = c.id','LEFT')
                ->join('portal_category_post c_p','p.id = c_p.post_id','LEFT')
                ->where('p.post_title','like','%'.$keyword.'%')
                ->where('c_p.category_id','<>',CityCategoryModel::xqyy)
                ->where('c_p.category_id','<>',CityCategoryModel::xyhl)
                ->where('p.delete_time', 0)
                ->field('p.id,p.post_title,p.post_excerpt,p.post_favorites,c.name city_name')
                ->order('p.weigh desc')
                ->paginate($limit,false,['query'=>request()->param()]);
            $data = $res->toArray();
            $page = $res->render();

            $post_ids = array_column($data['data'],'id');
            //查找分类名称
            $category = Db::name('portal_category_post')
                ->alias('c_p')
                ->join('portal_category c','c_p.category_id = c.id','LEFT')
                ->whereIn('c_p.post_id',$post_ids)
                ->field('c.id,c_p.post_id,c.name')
                ->select()
                ->toArray();
            foreach($data['data'] as &$value){
                $value['post_title'] = str_replace($keyword,'<span style="color:rgba(9, 255, 142, 1);">'.$keyword.'</span>',$value['post_title']);
                foreach($category as $item){
                    if($value['id'] == $item['post_id']){
                        $value['category_name'] = $item['name'];
                        $value['post_url'] = $this->getDetailUrl($item['id']);
                    }
                }
            }

            //查询总数
            $count = Db::name('portal_post')
                ->alias('p')
                ->join('portal_category_post c_p','p.id = c_p.post_id','LEFT')
                ->where('p.post_title','like','%'.$keyword.'%')
                ->where('c_p.category_id','<>',CityCategoryModel::xqyy)
                ->where('c_p.category_id','<>',CityCategoryModel::xyhl)
                ->where('p.delete_time', 0)
                ->count();
        }else{
            $count = 0;
            $data['data'] = [];
            $page = '';
        }
        $this->assign('count',$count);
        $this->assign('res',$data['data']);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //获取各个板块详情页位置
    public function getDetailUrl($c_id){
        $url = '';
        switch ($c_id) {
            case CityCategoryModel::xqgs:
                $url = '/portal/star/getStoryDetail';
                break;
            case CityCategoryModel::whmj:
                $url = '/portal/star/getSceneryDetail';
                break;
            case CityCategoryModel::yyzx:
                $url = '/portal/star/getFoodDetail';
                break;
            case CityCategoryModel::lsmq:
                $url = '/portal/star/getHotelDetail';
                break;
            case CityCategoryModel::hlst:
                $url = '/portal/star/getEcologyDetail';
                break;
            case CityCategoryModel::blcx:
                $url = '/portal/star/getTravelDetail';
                break;
            case CityCategoryModel::mxft:
                $url = '/portal/region/getStarDetail';
                break;
            case CityCategoryModel::djkb:
                $url = '/portal/region/getNewsDetail';
                break;
            case CityCategoryModel::djrz:
                $url = '/portal/region/getNoteDetail';
                break;
            case CityCategoryModel::tqwl:
                $url = '/portal/region/getFutureDetail';
                break;
            case CityCategoryModel::qlxc:
                $url = '/portal/enjoy/getEnjoyDetail';
                break;
            case CityCategoryModel::sjmy:
                $url = '/portal/enjoy/getEnjoyDetail';
                break;
            case CityCategoryModel::stsy:
                $url = '/portal/enjoy/getEnjoyDetail';
                break;
            case CityCategoryModel::hwtt:
                $url = '/portal/enjoy/getEnjoyDetail';
                break;
            case CityCategoryModel::lylx:
                $url = '/portal/scout/getTravelDetail';
                break;
            case CityCategoryModel::ddfw:
                $url = '/portal/scout/getSceneryDetail';
                break;
            case CityCategoryModel::cysj:
                $url = '/portal/scout/getSceneryDetail';
                break;
            case CityCategoryModel::yjyr:
                $url = '/portal/scout/getSceneryDetail';
                break;
            default:
        }
        return $url;
    }

    //第三方微信登录
    public function wx_login(){
        $config = Config::get('wx_login');
        $app_id = $config['app_id'];
        $redirect_uri = $config['redirect_uri'];
        $scope = $config['scope'];
        $state = md5(uniqid(rand(), TRUE));
        $url = 'https://open.weixin.qq.com/connect/qrconnect?appid='.$app_id.'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
        $res = $this->http_get($url);
        var_dump(11);
        var_dump($res);exit;
    }

    //curl  get请求
    public function http_get($url){
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false);//不开启header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }

    //curl post请求
    public function http_post($url,$data,$headers){
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, true); // 开启header
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//请求头部
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }
}