HomeBaseController.php 12.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use app\portal\model\PortalCategoryModel;
use app\portal\model\PageModel;
use app\portal\model\ShowModel;
use app\portal\model\WebdataModel;
use app\user\model\UserModel;
use think\Db;
use app\admin\model\ThemeModel;
use think\Session;
use think\View;

class HomeBaseController extends BaseController
{

    public function _initialize()
    {
        // 监听home_init
        hook('home_init');
        parent::_initialize();
        $siteInfo = cmf_get_site_info();
        View::share('site_info', $siteInfo);
        //查询主导航
        Self::selectNav();
        //获取网站配置信息
        Self::getSiteInfo();
        //获取剩余天数
        Self::getStartTime();
        //获取支持单位
        Self::getUnit();
        //获取登录信息
        Self::getUserLoginInfo();
        //获取banner
        Self::getBanner();

    }

    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 . $request->action();
                } 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)) {
            $this->error("用户尚未登录", url("user/login/index"));
        }
    }

    /**
     *  API返回信息格式函数 ;0失败,1成功
     * @param string $code
     * @param string $message
     * @param array $data
     */
    public function apiResponse($code = '', $msg = '',$data = array()){
        header('Access-Control-Allow-Origin: *');
        header('Content-Type:application/json; charset=utf-8');
        $result = array(
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data,
        );
        die(json_encode($result,JSON_UNESCAPED_UNICODE));
    }

    /**
     * 查询主导航
     */
    public function selectNav()
    {
        $menu_id = $this->request->param('menu_id','1','intval');
        $nav_id = 1; //主导航
        $navMenuModel = Db::name('nav_menu');
        $list = $navMenuModel
            ->field('id,parent_id,name,href')
            ->where([
                'nav_id' => $nav_id,
                'parent_id' => 0,
                'status' => 1
            ])
            ->order('list_order ASC')
            ->select()->toArray();
        foreach ($list as $k=>$v){
            $list[$k]['son'] = $navMenuModel
                ->field('id,name,href')
                ->where([
                    'parent_id' => $v['id'],
                    'status' => 1
                ])->select()->toArray();
        }
        $parent_id = $navMenuModel->where('id',$menu_id)->value('parent_id');
        $this->assign('nav_list',$list);
        $this->assign('menu_id',$menu_id);
        $this->assign('parent_id',$parent_id);
    }

    /**
     *  获取网站信息
     */
    public function getSiteInfo()
    {
        $site_info = cmf_get_site_info();
        $this->assign('site_info',$site_info);
    }

    /**
     *  获取banner
     */
    public function getBanner()
    {
        $banner = Db::name('slide_item')
            ->field('image,url')
            ->where('slide_id',2)
            ->select();
        $this->assign('banner',$banner);
    }
    /**
     * 获取剩余天数
     */
    public function getStartTime()
    {
        $webDatamodel = new WebdataModel();
        //展会开始时间
        $start_time = $webDatamodel->value('start_time');
        //剩余时间的时间戳
        $last_time = $start_time - time();
        if($last_time < 0){
            $last_day = 0;
        }else{
            $last_day = floor($last_time/86400);
            $last_day = str_split($last_day);
        }
        $this->assign('last_day',$last_day);
    }


    /**
     * 获取支持单位
     */
    public function getUnit()
    {
        $showModel = new ShowModel();
        //主办单位
        $unit1 = $showModel
            ->where('cate_id',47)
            ->select();
        //承办单位
        $unit2 = $showModel
            ->where('cate_id',48)
            ->select();
        //支持单位
        $unit3 = $showModel
            ->where('cate_id',49)
            ->select();
        //组织机构
        $unit4 = $showModel
            ->where('cate_id',50)
            ->select();

        $this->assign('unit1',$unit1);
        $this->assign('unit2',$unit2);
        $this->assign('unit3',$unit3);
        $this->assign('unit4',$unit4);
    }

    /**
     * page表加访问量
     * @param $id
     * @return int|true
     */
    public function setPageNum($id)
    {
        $pageModel = new PageModel();
        $res = $pageModel->where('id',$id)->setInc('click_num',1);
        return $res;
    }

    /**
     * show表加访问量
     * @param $id
     * @return int|true
     */
    public function setShowNum($id)
    {
        $showModel = new ShowModel();
        $res = $showModel->where('id',$id)->setInc('click_num',1);
        return $res;
    }

    /**
     * category表加访问量
     * @param $id
     * @return int|true
     */
    public function setCateNum($id)
    {
        $cateModel = new PortalCategoryModel();
        $res = $cateModel->where('id',$id)->setInc('click_num',1);
        return $res;
    }

    /**
     * 获取前台分页样式
     * @param $list 分页后得到的数据
     * @return string
     */
    public function getPageStyle($list,$keyword = '')
    {
        $url = $list->getCurrentPath(); //当前path
        $lastPageNum = $list->lastPage(); // 总页数
        $thisPageNum = $list->getCurrentPage(); //当前页码
        $firstUrl = $url . '?page=1&keyword=' . $keyword;
        $lastUrl = $url . '?page=' . $lastPageNum . "&keyword=" . $keyword;
        $nextUrl = $url . '?page=' . $thisPageNum . "&keyword=" . $keyword;
        $firstPage = '<li class="fenye_frist"><a href='.$firstUrl.'>首页</a></li>';
        $lastPage = '<li  class="fenye_frist"><a href='.$lastUrl.'>末页 </a></li>';
        $nextPage = '<li  class="fenye_frist"><a href='.$nextUrl.'>下一页 </a></li>';
        $middlePage = '';
        for ($i=1;$i<$lastPageNum+1;$i++){
            $thisurl = $url . '?page=' . $i . "&keyword=" . $keyword;
            if($i == $thisPageNum){
                $middlePage .= "<li class='fenye_active'><a href='$thisurl'>$i</a></li>";
            }else{
                $middlePage .= "<li class='fenye_num'><a href='$thisurl'>$i</a></li>";
            }
        }
        $page = $firstPage . $middlePage . $nextPage .$lastPage;
        return $page;
    }

    /**
     * 获取登录信息
     */
    public function getUserLoginInfo()
    {
        $user_mobile = Session::get('user_mobile');
        $user_mobile = empty($user_mobile)?'0':$user_mobile;
        $this->assign('user_mobile',$user_mobile);
    }

}