HomeBaseController.php 11.4 KB
<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use think\Db;
use app\admin\model\ThemeModel;
use think\View;
use think\Config;

class HomeBaseController extends BaseController
{

    public function _initialize()
    {
        require_once VENDOR_PATH . 'wxjssdk/jssdk.php';
        //微信分享接口调用
        $jssdk       = new \JSSDK(config::get("WECHAT_APPID"), config::get("WECHAT_APPSECRET"));
        $signPackage = $jssdk->GetSignPackage();
        $AccessToken = $jssdk->getAccessToken();
        //微信接口取值
        $share['wxappId']     = $signPackage["appId"];
        $share['wxtimestamp'] = $signPackage["timestamp"];
        $share['wxnonceStr']  = $signPackage["nonceStr"];
        $share['wxsignature'] = $signPackage["signature"];
        $share['appid']       = config::get("WECHAT_APPID");

        $this->assign("wx_js_sdk", $share);

        if (!session('wechat_login')) {

            $p_code = $this->request->param("code");

            if (!$p_code) {
                $APPID        = config::get("WECHAT_APPID");
                $REDIRECT_URI = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

                //微信登录静默与否
                $scope = 'snsapi_userinfo';
                $url   = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $APPID . '&redirect_uri=' . urlencode($REDIRECT_URI) . '&response_type=code&scope=' . $scope . '&state=' . 'STATE' . '#wechat_redirect';
                header("Location:" . $url);
                die();
            } else {
                $appid         = config::get('WECHAT_APPID');
                $secret        = config::get('WECHAT_APPSECRET');
                $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $p_code . '&grant_type=authorization_code';

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $get_token_url);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                $res = curl_exec($ch);
                curl_close($ch);

                //解析openid-json
                $user_obj  = json_decode($res, true);
                $w_info_ak = $user_obj['access_token'];
                $openid    = $user_obj['openid'];


                //检查数据库是否已存储用户信息
                $exist_res = Db::table('qnb_user')->where(['openid' => $openid])->find();
                if (!$exist_res) {
                    $get_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $w_info_ak . '&openid=' . $openid . '&lang=zh_CN';
                    $ch           = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $get_info_url);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                    $res = curl_exec($ch);
                    curl_close($ch);

                    //解析user-info-json
                    $user_info_obj             = json_decode($res, true);
                    $datain['openid']          = $openid;
                    $datain['user_nickname']   = $user_info_obj['nickname'];
                    $datain['sex']             = $user_info_obj['sex'];
                    $datain['country']         = $user_info_obj['country'];
                    $datain['province']        = $user_info_obj['province'];
                    $datain['city']            = $user_info_obj['city'];
                    $datain['headimgurl']      = $user_info_obj['headimgurl'];
                    $datain['last_login_time'] = time();
                    $datain['create_time']     = time();
                    $datain['user_type']       = '2';
                    $datain['last_login_ip']   = $this->request->ip();

                    //入库个人信息,缓存openid
                    $ins_res = Db::table('qnb_user')->insert($datain);
                    if ($ins_res) {
                        session('wechat_login', 1);
                        session('openid', $user_info_obj['openid']);
                    }
                } else {
                    //更新登录时间ip,缓存openid
                    $dataup['last_login_time'] = time();
                    $dataup['last_login_ip']   = $this->request->ip();
                    $ins_res                   = Db::table('qnb_user')->where(['openid' => $openid])->update($dataup);
                    if ($ins_res) {
                        session('wechat_login', 1);
                        session('openid', $openid);
                    }
                }
            }
        }


        // 监听home_init
        hook('home_init');
        parent::_initialize();
        $siteInfo = cmf_get_site_info();
        View::share('site_info', $siteInfo);
    }

    public function _initializeView()
    {
        $cmfThemePath    = config('cmf_theme_path');
        $cmfDefaultTheme = cmf_get_current_theme();

        $themePath = "{$cmfThemePath}{$cmfDefaultTheme}";

        $root = cmf_get_root();
        //使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$root}/{$themePath}",
                '__STATIC__'   => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', "{$themePath}/");
        config('view_replace_str', $viewReplaceStr);

        $themeErrorTmpl = "{$themePath}/error.html";
        if (file_exists_case($themeErrorTmpl)) {
            config('dispatch_error_tmpl', $themeErrorTmpl);
        }

        $themeSuccessTmpl = "{$themePath}/success.html";
        if (file_exists_case($themeSuccessTmpl)) {
            config('dispatch_success_tmpl', $themeSuccessTmpl);
        }


    }

    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array $vars 模板输出变量
     * @param array $replace 模板替换
     * @param array $config 模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        $template = $this->parseTemplate($template);
        $more     = $this->getThemeFileMore($template);
        $this->assign('theme_vars', $more['vars']);
        $this->assign('theme_widgets', $more['widgets']);
        return parent::fetch($template, $vars, $replace, $config);
    }

    /**
     * 自动定位模板文件
     * @access private
     * @param string $template 模板文件规则
     * @return string
     */
    private function parseTemplate($template)
    {
        // 分析模板文件规则
        $request = $this->request;
        // 获取视图根目录
        if (strpos($template, '@')) {
            // 跨模块调用
            list($module, $template) = explode('@', $template);
        }

        $viewBase = config('template.view_base');

        if ($viewBase) {
            // 基础视图目录
            $module = isset($module) ? $module : $request->module();
            $path   = $viewBase . ($module ? $module . DS : '');
        } else {
            $path = isset($module) ? APP_PATH . $module . DS . 'view' . DS : config('template.view_path');
        }

        $depr = config('template.view_depr');
        if (0 !== strpos($template, '/')) {
            $template   = str_replace(['/', ':'], $depr, $template);
            $controller = cmf_parse_name($request->controller());
            if ($controller) {
                if ('' == $template) {
                    // 如果模板文件名为空 按照默认规则定位
                    $template = str_replace('.', DS, $controller) . $depr . cmf_parse_name($request->action(true));
                } elseif (false === strpos($template, $depr)) {
                    $template = str_replace('.', DS, $controller) . $depr . $template;
                }
            }
        } else {
            $template = str_replace(['/', ':'], $depr, substr($template, 1));
        }
        return $path . ltrim($template, '/') . '.' . ltrim(config('template.view_suffix'), '.');
    }

    /**
     * 获取模板文件变量
     * @param string $file
     * @param string $theme
     * @return array
     */
    private function getThemeFileMore($file, $theme = "")
    {

        //TODO 增加缓存
        $theme = empty($theme) ? cmf_get_current_theme() : $theme;

        // 调试模式下自动更新模板
        if (APP_DEBUG) {
            $themeModel = new ThemeModel();
            $themeModel->updateTheme($theme);
        }

        $themePath = config('cmf_theme_path');
        $file      = str_replace('\\', '/', $file);
        $file      = str_replace('//', '/', $file);
        $file      = str_replace(['.html', '.php', $themePath . $theme . "/"], '', $file);

        $files = Db::name('theme_file')->field('more')->where(['theme' => $theme])->where(function ($query) use ($file) {
            $query->where(['is_public' => 1])->whereOr(['file' => $file]);
        })->select();

        $vars    = [];
        $widgets = [];
        foreach ($files as $file) {
            $oldMore = json_decode($file['more'], true);
            if (!empty($oldMore['vars'])) {
                foreach ($oldMore['vars'] as $varName => $var) {
                    $vars[$varName] = $var['value'];
                }
            }

            if (!empty($oldMore['widgets'])) {
                foreach ($oldMore['widgets'] as $widgetName => $widget) {

                    $widgetVars = [];
                    if (!empty($widget['vars'])) {
                        foreach ($widget['vars'] as $varName => $var) {
                            $widgetVars[$varName] = $var['value'];
                        }
                    }

                    $widget['vars']       = $widgetVars;
                    $widgets[$widgetName] = $widget;
                }
            }
        }

        return ['vars' => $vars, 'widgets' => $widgets];
    }

    public function checkUserLogin()
    {
        $userId = cmf_get_current_user_id();
        if (empty($userId)) {
            if ($this->request->isAjax()) {
                $this->error("您尚未登录", cmf_url("user/Login/index"));
            } else {
                $this->redirect(cmf_url("user/Login/index"));
            }
        }
    }

}