<?php
if (!defined('puyuetian')) {
    exit('403');
}

// preload
(function () {
    //定义全局编码，防止个别exit输出乱码
    header('Content-Type: text/html; charset=utf-8');
    //防止跨站攻击
    // header('X-Frame-Options: SAMEORIGIN');

    //设置备份，用于后台
    set([
        'embed_headmarks_old' => set('embed_headmarks'),
        'embed_head_old'      => set('embed_head'),
        'embed_foot_old'      => set('embed_foot'),
        'pctemplatename'      => set('templatename'),
        'webtitle_old'        => set('webtitle'),
        'webkeywords_old'     => set('webkeywords'),
        'webdescription_old'  => set('webdescription'),
    ]);

    //手机域名？
    $domain          = sys('domain');
    $domains         = explode('.', $domain);
    $phonedomains    = set('phonedomains');
    $ifpccomephonego = set('ifpccomephonego');
    if (InArray($phonedomains, $domains[0]) || ($ifpccomephonego && isphonecome())) {
        if (2 == $ifpccomephonego && !InArray($phonedomains, $domains[0]) && 1 != input('get._phonenogo/d')) {
            if (count($domains) > 2) {
                $mpurl = 'http://' . current(explode(',', $phonedomains)) . '.' . substr($domain, strlen($domains[0]) + 1);
            } else {
                $mpurl = 'http://' . current(explode(',', $phonedomains)) . '.' . $domain;
            }
            ExitGourl("{$mpurl}{$_SERVER['PHP_SELF']}?{$_SERVER['QUERY_STRING']}");
        }
        set([
            'templatename'     => set('phonetemplatename'),
            'defaulttemplates' => set('phonedefaulttemplates'),
            'defaultpage'      => set('phonedefaultpage'),
        ]);
    }

    // v8版本标识
    g([
        'v8'            => true,
        'template.main' => 'main',
        'template.head' => 'head',
        'template.body' => 'body',
        'template.foot' => 'foot',
    ]);

    // 当前加载的模板是否为v8版本
    if (file_exists(PK_TEMPLATE_PATH . set('templatename') . '/hadsky.v8')) {
        set('is_v8_template', 1);
    } else {
        set('is_v8_template', 0);
    }

    // 当前php include的文件路径
    set('php_include_path', (function () {
        $c     = g('get.c') ? g('get.c') : set('defaultpage');
        $is_v8 = set('is_v8_template') && (file_exists(PK_TEMPLATE_PATH . set('templatename') . '/' . $c . '.hst') || (function ($c) {
            if (!set('defaulttemplates')) {
                return false;
            }
            $dts = explode(',', set('defaulttemplates'));
            foreach ($dts as $dt) {
                if (!file_exists(PK_TEMPLATE_PATH . $dt . '/' . $c . '.hst') && !file_exists(PK_TEMPLATE_PATH . $dt . '/' . $c . '-1.hst')) {
                    continue;
                }
                return file_exists(PK_TEMPLATE_PATH . $dt . '/hadsky.v8');
            }
            return false;
        })($c));
        return PK_PHP_PATH . 'include/v' . ($is_v8 ? '8' : '7') . $c . '.php';
    })());
})();

// uia
(function () {
    /*
     * 用户登录检测，若登录用户信息保存在$_G['USER']数组内
     * $_G['USER']['ID']为$LoginUserId的简写
     * $_G['USER']为$LoginUserArray的简写
     */

    //user auto login
    //用户身份验证
    g('user', UIA());

    //读取用户组数据
    if (user('id') && user('groupid')) {
        g('usergroup', table('usergroup')->where(user('groupid'))->find());
        if (usergroup()) {
            // standardArray($_G['USERGROUP']);
            g('user.usergroupname', usergroup('usergroupname'));
            if (usergroup('readlevelmax')) {
                if (usergroup('readlevel') > user('readlevel')) {
                    g('user.readlevel', usergroup('readlevel'));
                } else {
                    g('usergroup.readlevel', user('readlevel'));
                }
            } else {
                g('user.readlevel', usergroup('readlevel'));
            }
            g('user.usergroupquanxian', usergroup('quanxian'));
            $data = json_decode(usergroup('data'), true);
            foreach ($data as $key => $value) {
                g('user.data', JsonData(user('data'), $key, $value));
            }
        }
    } else {
        g('usergroup', false);
    }

//当前用户未读消息数
    if (user('id')) {
        if (table('user_message')->where([
            'islook' => 0,
            'uid'    => user('id'),
        ])->find('id')) {
            g('usermessage.unreadcount', 1);
        }
        // 该用户是否允许登录
        if (!InArray(getUserQX(), 'login')) {
            UserLogout(true);
            setcookie('USERNAME', '', time() - 3600);
            setcookie('PASSWORD', '', time() - 3600);
            setcookie('SESSION_TOKEN', '', time() - 3600);
            PkPopup('{
            content:"您已被禁止登录请联系管理员处理",
            icon:2,
            shade:1,
            nomove:1,
            hideclose:1,
            submit:function(){
                location.href="index.php"
            }
        }');
        }
    } else {
        g([
            'user.id'                 => 0,
            'usermessage.unreadcount' => 0,
        ]);
    }

    //防止csrf攻击
    g('chkcsrfval', md5(key_endecode(md5(user('session_token')))));

//用户数据前端化
    $showstrs = explode(',', 'id,groupid,username,sex,nickname,tiandou,jifen,readlevel,quanxian,birthday,email,qq,phone,sign,friends,idol,fans,collect,usergroupname,usergroupquanxian');
    $_ud      = user();
    standardArray($_ud);
    foreach ($_ud as $key => $value) {
        if (!InArray($showstrs, strtolower($key))) {
            unset($_ud[$key]);
        }
    }
    $_ud['CHKCSRFVAL']          = g('chkcsrfval');
    $_ud['MESSAGE_UNREADCOUNT'] = g('usermessage.unreadcount');
    $_ud['C']                   = g('get.c');
//设置数据前端化
    $showstrs = explode(',', 'quotes,templatename,pctemplatename,webdescription,webkeywords,weblogo,readlistnum,replylistnum,logotext,uploadfiletypes,uploadfilesize,postreadjifen,postreadtiandou,postreplyjifen,postreplytiandou,defaultpage,rewriteurl,phonetemplatename,jifenname,tiandouname,regjifen,regtiandou,postingtimeinterval,postaudit,newuserpostwaittime,beianhao,bbcodeattrs,readtitlemin,readtitlemax,readcontentmin,readcontentmax,replycontentmin,replycontentmax,replyorder,readtopnum,webtitle,defaulttemplates,novicetraineetime,postreadcheck,postreplycheck,changeuserinfoverify,readlistorder,readlistshowbks,readlisthiddenbks,showmessagecount,regreadlevel,uploadheadsize,phonedomains,ifpccomephonego,usernameeverychars,phonedefaulttemplates,phonedefaultpage,activetopreadids,postmessagemaxnum,app_hadskycloudserver_sms_open,regnoemail,is_v8_template');
    $_set     = set();
    standardArray($_set);
    foreach ($_set as $key => $value) {
        if (!InArray($showstrs, strtolower($key))) {
            unset($_set[$key]);
        }
    }
    $_get = g('get');
    standardArray($_get);
    setConcat('embed_headmarks', '<script>var $_USER=' . json_encode($_ud) . ',$_SET=' . json_encode($_set) . ',$_URI=' . json_encode($_get) . ';if($_URI===null){$_URI=[]}</script>');
})();

// normal
(function () {
    //站点状态
    if (set('sitestatus') && !InArray('login,chklogin,app', g('get.c')) && 1 != user('id')) {
        g('htmlcode.main', template('siteclosed', true));
        template(g('template.main'));
        exit();
    }

    //注入及xss防护，地址安全检测
    $safe_request_uri = set('safe_request_uri');
    if ($safe_request_uri && 1 != user('id')) {
        if (2 == $safe_request_uri && (!StringSafeCheck($_SERVER['REQUEST_URI'])) || (1 == $safe_request_uri && !GetSafeCheck())) {
            //记录日志
            $fp  = sys('path') . 'logs/attack/' . date('Y-m-d') . '.csv';
            $qq  = urldecode(urldecode($_SERVER['REQUEST_URI']));
            $str = '';
            if (!file_exists($fp)) {
                $str .= '"日期","时间","IP","UID","请求"' . "\n";
            }
            $str .= date('"Y-m-d","H:i:s","') . getClientInfos('ip') . '","' . user('id') . '","' . str_replace('"', '""', $qq) . "\"\n";
            file_put_contents($fp, iconv("UTF-8", "gb2312//IGNORE", $str), FILE_APPEND);
            //弹出提示
            PkPopup('{
                title:"警告",
                content:"您的请求包含非法字符，已被系统阻止",
                icon:2,
                close:function(){
                    location.href="index.php"
                },
                hideclose:1,
                shade:1
            }');
        }
    }
})();

// loadapps
(function () {
    $loadinfo = '';
    $total    = 0;
    foreach (set() as $key => $value) {
        $len = strlen($key);
        if ($len > 9 && substr($key, 0, 4) == 'app_' && substr($key, $len - 5) == '_load' && $value) {
            //符合加载条件，获取app目录
            $aname = strtolower(substr($key, 4, $len - 9));
            $loads = explode(',', $value);
            foreach ($loads as $load) {
                if (!InArray('0,1', $load)) {
                    $apath = PK_APP_PATH . "{$aname}/{$load}.php";
                    // v8.0
                    sys([
                        'appdir'  => $aname,
                        'appfile' => $load,
                        'apppath' => $apath,
                    ]);
                    if (file_exists($apath)) {
                        (function ($APP_LOAD_PATH) {
                            global $_G, $postarray, $regarray;
                            require $APP_LOAD_PATH;
                        })($apath);
                        $total++;
                        $loadinfo .= "加载成功:\"{$aname}:{$load}\"\n";
                    } else {
                        $loadinfo .= "加载出错:\"{$aname}:{$load}\"不存在\n";
                    }
                }
            }

        }
    }
    $loadinfo .= "共成功加载HadSky插件{$total}个\n";
    g([
        'app.loadinfo' => $loadinfo,
        'app.total'    => $total,
    ]);
})();
