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

/*
 * 用户自定义函数
 */
function newBBcode($content, $type = 'read', $userqxs = null, $userdata = null, $return = '[Image]')
{
    global $_G;
    if (null === $userqxs) {
        $userqxs = getUserQX();
    }
    if (null === $userdata) {
        $userdata = getUserQX(false, 'data');
    }
    $r = '';
    if ('read' == $type || 'reply' == $type) {
        if (InArray($userqxs, 'htmlcode')) {
            $r = $content;
        } elseif (InArray($userqxs, 'bbcode')) {
            $bbcode = JsonData($userdata, 'htmlcodemarks');
            $bbattr = JsonData($userdata, 'htmlcodeattrs');
            if (!$bbcode) {
                $bbcode = false;
            }
            if (!$bbattr) {
                $bbattr = false;
            }
            $r = BBcode($content, $bbcode, $bbattr);
        } else {
            $r = htmlspecialchars(strip_tags($content, ''));
        }
    } elseif ('sign' == $type) {
        if (InArray($userqxs, 'sign')) {
            $bbcode = JsonData($userdata, 'signcodemarks');
            $bbattr = JsonData($userdata, 'signcodeattrs');
            if (!$bbcode) {
                $bbcode = false;
            } else {
                $bbcode = $_G['SET']['SIGNCODEMARKS'];
            }
            if (!$bbattr) {
                $bbattr = false;
            } else {
                $bbattr = $_G['SET']['SIGNCODEATTRS'];
            }
            $r = BBcode($content, $bbcode, $bbattr);
        }
    }
    if (!$r) {
        $r = $return;
    }
    return $r;
}

function NewMessage($uid, $content, $fid = 0, $safetype = 0)
{
    global $_G;
    $array['uid'] = Cnum($uid);
    $array['fid'] = Cnum($fid);
    if (0 == $safetype) {
        $array['content'] = htmlspecialchars(strip_tags($content), ENT_QUOTES);
    } elseif (1 == $safetype) {
        $array['content'] = BBcode($content);
    } else {
        $array['content'] = $content;
    }
    $array['addtime'] = time();
    $array['islook']  = 0;
    $_G['TABLE']['USER_MESSAGE']->newData($array);
}

function getZoneTimeline($uid)
{
    global $_G;
    $__oldid = $_G['TABLE']['READ']->getOldId("where `uid`={$uid}");
    $__newid = $_G['TABLE']['READ']->getNewId("where `uid`={$uid}");
    if ($__oldid && $__newid) {
        $__newtime = $_G['TABLE']['READ']->getData($__newid);
        $__oldtime = $_G['TABLE']['READ']->getData($__oldid);
        $__newtime = date('Ym', $__newtime['posttime']);
        $__oldtime = date('Ym', $__oldtime['posttime']);
        for ($__i = 0; ($__oldtime < $__newtime) && $__i < ZONE_TIMELINENUM; $__i++) {
            $ZONE_TIMELINE .= "
				<a class='blog-timeline-a' href='" . ReWriteURL('zone', "uid={$uid}&timeline={$__newtime}&page=1") . "'>
					" . substr($__newtime, 0, 4) . '年' . substr($__newtime, strlen($__newtime) - 2) . "月
				</a>
				";
            if (substr($__newtime, strlen($__newtime) - 2) == '01') {
                //若当前为1月，上一月则为上一年12月
                $__newtime = intval((substr($__newtime, 0, 4) - 1) . '12');
            } else {
                $__newtime--;
            }
        }
    }
    return $ZONE_TIMELINE;
}

/**
 * 用户积分、天豆操作函数
 * @param int $jifen 积分改变数
 * @param int $tiandou 天豆改变数
 * @param string $content 改动说明
 * @param int $uid 被改动的用户id
 */
function userJTChange(int $jifen = 0, int $tiandou = 0, $content = '', $uid = 0)
{
    if (!$uid) {
        $uid = user('id');
    }
    if (!$jifen && !$tiandou) {
        return '参数错误';
    }
    $user = table('user')->where($uid)->find();
    if (!$user) {
        return '用户不存在';
    }
    if ($jifen < 0 && $user['jifen'] + $jifen < 0) {
        return '用户' . set('jifenname') . '不足';
    }
    if ($tiandou < 0 && $user['tiandou'] + $tiandou < 0) {
        return '用户' . set('tiandouname') . '不足';
    }
    $arr = [
        'id'      => $uid,
        'jifen'   => ['+', $jifen],
        'tiandou' => ['+', $tiandou],
    ];
    if (!table('user')->update($arr)) {
        return table()->error();
    }
    // 记录变动
    table('jtrecord')->insert([
        'uid'     => $uid,
        'time'    => time(),
        'jifen'   => $jifen,
        'tiandou' => $tiandou,
        'content' => $content,
    ]);
    return true;
}

function UserDataChange($array, $uid = false, $way = '+', $content = '')
{
    global $_G;
    if (false === $uid) {
        $uid = $_G['USER']['ID'];
    }
    if (!$uid) {
        return false;
    }
    $record = [
        'uid'     => $uid,
        'time'    => time(),
        'content' => $content,
    ];
    if (!$way) {
        return false;
    }
    $olddata = $_G['TABLE']['USER']->getData($uid);
    if (!$olddata) {
        return false;
    }
    $is_record = false;
    foreach ($array as $key => $value) {
        if (InArray('jifen,tiandou', $key)) {
            $is_record    = true;
            $record[$key] = Cnum(str_replace([
                '++', '+-', '-+', '--',
            ], [
                '', '-', '-', '',
            ], "{$way}{$value}"));
        }
        if ('+' == $way) {
            $array[$key] = $olddata[$key] + $value;
        } elseif ('-' == $way) {
            $array[$key] = $olddata[$key] - $value;
        }
    }
    if ($is_record) {
        // 智能化积分变动提示
        if (!$record['content'] && sys('appconfig')) {
            $record['content'] = '【' . sys('appconfig')['title'] . '】使用变动';
        }
        // 记录交易
        table('jtrecord')->insert($record);
    }
    $array['id'] = $uid;
    return $_G['TABLE']['USER']->NewData($array);
}

//版块遍历函数，调用前需定义childs=-1;
function foundchildforum($pid)
{
    global $_G, $postnewreadforumlist, $childs;
    //echo $childs;
    $data = $_G['TABLE']['READSORT']->getDatas(0, 0, "where `pid`={$pid} order by `rank`");
    if ($data) {
        $childs++;
        foreach ($data as $array) {
            $fgf = $sqx = $disabled = '';
            for ($i = 0; $i < $childs; $i++) {
                $fgf .= '--';
            }
            if ($_G['USER']['READLEVEL'] < $array['postlevel']) {
                $sqx      = " 需阅读权限达到：{$array['postlevel']}";
                $disabled = " disabled";
            }
            $postnewreadforumlist .= "<option value='{$array['id']}'{$disabled}>{$fgf}{$array['title']}{$sqx}</option>";
            foundchildforum($array['id']);
            if (0 == $pid) {
                $childs = 0;
            }
        }
    }
}

//插件前台加载函数
function LoadHadSkyPlugHOOKHTML($html)
{
    global $_G;
    //读取插件数据
    if ($_G['PLUG']['DATA'][$_G['SYSTEM']['CLOADPLUGNAME']]) {
        $__temp = $_G['PLUG']['DATA'][$_G['SYSTEM']['CLOADPLUGNAME']]['P'];
        if ($__temp) {
            $__temp = explode(',', $__temp);
            foreach ($__temp as $__value) {
                $__show = explode(':', $__value);
                if (count($__show) == 2) {
                    $_G['HOOK'][strtoupper($__show[0])][strtoupper($__show[1])] .= $html;
                }
            }
        }
    }
}

function restoreCycle($ids, $type = 'cycle')
{
    if (is_array($ids)) {
        $ids = implode(',', $ids);
    }
    $datas = table($type)->where('id', 'IN', $ids)->select();
    if (!$datas) {
        return false;
    }
    foreach ($datas as $data) {
        $table  = $data['tn'];
        $rrdata = json_decode($data['data'], true);
        if (!table($table)->insert($rrdata)) {
            continue;
        }
        table($type)->where($data['id'])->delete();
        // 审核通过的积分到账
        if ('audit' != $type) {
            continue;
        }
        if ('read' == $table) {
            $fid = $rrdata['sortid'];
        } else {
            if ('reply' == $table) {
                $readdata = table('read')->where($rrdata['rid'])->find();
            } else {
                $replydata = table('reply')->where($rrdata['rid'])->find();
                $readdata  = table('read')->where($replydata['rid'])->find();
            }
            $fid = $readdata['sortid'];
        }
        $forumdata = table('readsort')->where($fid)->find();
        $jf        = Cnum($forumdata["post{$table}jifen"]);
        $td        = Cnum($forumdata["post{$table}tiandou"]);
        if (!$jf) {
            $jf = Cnum(set("post{$table}jifen"));
        }
        if (!$td) {
            $td = Cnum(set("post{$table}tiandou"));
        }
        // 这里jifen和天豆必须都大于0，因为小于0的提前加减了
        if ($jf >= 0 && $td >= 0 && $rrdata['uid']) {
            userJTChange($jf, $td, '发布' . ('read' == $table ? '文章' : '回复') . '审核通过', $rrdata['uid']);
        }
    }
    return true;
}

function moveToCycle($tn, $ids, $type = 'cycle')
{
    if (is_array($ids)) {
        $ids = implode(',', $ids);
    }
    $datas = table($tn)->where('id', 'IN', $ids)->select();
    foreach ($datas as $data) {
        if (!table($type)->insert([
            'tn'   => $tn,
            'data' => json_encode($data, 320),
            'time' => time(),
        ])) {
            continue;
        }
        table($tn)->where($data['id'])->delete();
        if ('read' == $tn) {
            // 删除回复
            $replys = table('reply')->where('rid', $data['id'])->select();
            foreach ($replys as $reply) {
                moveToCycle('reply', $reply['id']);
            }
        }
        if ('reply' == $tn) {
            // 删除楼中楼
            $replys = table('reply_reply')->where('rid', $data['id'])->select();
            foreach ($replys as $reply) {
                moveToCycle('reply_reply', $reply['id']);
            }
        }
    }
    return true;
}

function Post(&$postarray, $type = 'read', $mc = false)
{
    global $_G;
    if (!$postarray['id']) {
        $postarray['id'] = Cnum($_G['GET']['ID'], 0, true, 0);
    }
    InArray(getUserQX(), 'admin') ? $admin       = true : $admin       = false;
    InArray(getUserQX(), 'superman') ? $superman = true : $superman = false;
    //编辑时检测版主
    if ($postarray['id']) {
        if ('reply' == $type) {
            $_ls    = $_G['TABLE']['REPLY']->getData($postarray['id']);
            $sortid = $_G['TABLE']['READ']->getData($_ls['rid']);
            $sortid = $sortid['sortid'];
        } else {
            $sortid = $_G['TABLE']['READ']->getData($postarray['id']);
            $sortid = $sortid['sortid'];
        }
        $bkdata                                                                            = $_G['TABLE']['READSORT']->getData($sortid);
        (InArray($bkdata['adminuids'], $_G['USER']['ID']) && $_G['USER']['ID']) ? $bkadmin = true : $bkadmin = false;
    }
    //检测帖子是否包含违禁词
    $wjcs = $_G['SET']['BANPOSTWORDS'];
    if ($wjcs && !InArray(getUserQX(), 'nobanpostwords')) {
        $wjcs = explode(',', $wjcs);
        foreach ($wjcs as $w) {
            if ($w) {
                if (strpos(str_replace(array("\n", "\r", "\r\n", "\t", " "), '', $_POST['title']), $w) !== false || strpos(str_replace(array("\n", "\r", "\r\n", "\t", " ", "&nbsp;"), '', strip_tags($_POST['content'])), $w) !== false) {
                    return "您的内容包含违禁词[{$w}]，无法发布";
                }
            }
        }
    }

    if ('read' == $type) {
        //========================文章发布及编辑=====================================
        if (!$postarray['title']) {
            $postarray['title'] = htmlspecialchars(trim($_POST['title']), ENT_QUOTES);
        }
        if (!$postarray['content']) {
            $postarray['content'] = newBBcode(trim($_POST['content']), $type, null, null, false);
        }
        if (!str_replace([' ', '&nbsp;'], '', $postarray['title'])) {
            return '标题不能为空';
        }
        if (!str_replace([' ', '&nbsp;'], '', $postarray['content'])) {
            return '内容不能为空';
        }
        $title_strlen   = mb_strlen($postarray['title']);
        $title_minlen   = Cnum($_G['SET']['READTITLEMIN'], 0, true, 0);
        $title_maxlen   = Cnum($_G['SET']['READTITLEMAX'], 0, true, 0);
        $content_strlen = mb_strlen($postarray['content']);
        $content_minlen = Cnum($_G['SET']['READCONTENTMIN'], 0, true, 0);
        $content_maxlen = Cnum($_G['SET']['READCONTENTMAX'], 0, true, 0);
        if ($title_minlen && $title_strlen < $title_minlen) {
            return "标题字数不能少于{$title_minlen}个字";
        }
        if ($title_maxlen && $title_strlen > $title_maxlen) {
            return "标题字数不能多于{$title_maxlen}个字";
        }
        if ($content_minlen && $content_strlen < $content_minlen) {
            return "内容字数不能少于{$content_minlen}个字";
        }
        if ($content_maxlen && $content_strlen > $content_maxlen) {
            return "内容字数不能多于{$content_maxlen}个字";
        }
        // 获取内容里面非表情的图片
        $images = getHtmlImages($postarray['content'], 0, 'emotion', true);
        $image  = '';
        foreach ($images as $v) {
            $image .= $v['src'] . ',';
        }
        $image              = trim($image, ',');
        $postarray['image'] = $image;
        // 获取内容里面视频
        $videos = getHtmlVideos($postarray['content'], 0);
        $video  = '';
        foreach ($videos as $v) {
            $video .= $v['src'] . ',';
        }
        $video              = trim($video, ',');
        $postarray['video'] = $video;
        // 获取内容里面音频
        $audios = getHtmlMarks($postarray['content'], 'audio');
        $audio  = '';
        foreach ($audios as $v) {
            $audio .= $v['src'] . ',';
        }
        $audio              = trim($audio, ',');
        $postarray['audio'] = $audio;
        if (!$postarray['sortid']) {
            $postarray['sortid'] = Cnum($_POST['sortid'], 0, true, 0);
        }
        if (!$postarray['label']) {
            $postarray['label'] = preg_replace('/[\'\"]+/', '', strip_tags($_POST['label']));
        }
        if (!$postarray['readlevel']) {
            $postarray['readlevel'] = Cnum($_POST['readlevel'], 0, true, 0, Cnum(getUserQX($_G['USER']['ID'], 'readlevel')));
        }
        if (InArray(getUserQX(), 'admin')) {
            if (!$postarray['top']) {
                $postarray['top'] = Cnum($_POST['top'], 0, true, 0, 1);
            }
            if (!$postarray['high']) {
                $postarray['high'] = Cnum($_POST['high'], 0, true, 0, 1);
            }
            if (!$postarray['locked']) {
                $postarray['locked'] = Cnum($_POST['locked'], 0, true, 0, 1);
            }
        }
        if (!$postarray['replyafterlook']) {
            $postarray['replyafterlook'] = Cnum($_POST['replyafterlook'], 0, true, 0, 1);
        }
        if (!$postarray['lookonlyme']) {
            $postarray['lookonlyme'] = Cnum($_POST['lookonlyme'], 0, true, 0, 1);
        }

        //非超级管理员管理员无法设置精华和置顶
        if (!$superman) {
            unset($postarray['high'], $postarray['top']);
        }

        if (InArray($_G['SET']['POSTREADTITLECOLORUSERGROUP'], $_G['USER']['GROUPID']) || !$_G['SET']['POSTREADTITLECOLORUSERGROUP']) {
            if (substr($_POST['titlecolor'], 0, 1) == '#' && strlen($_POST['titlecolor']) == 7 && Cstr(substr($_POST['titlecolor'], 1))) {
                $postarray['title'] = '<font class="pk-hadsky" color="' . $_POST['titlecolor'] . '">' . $postarray['title'] . '</font>';
            }
        }

        if ($postarray['id']) {
            //============================编辑文章===========================
            if (!InArray(getUserQX(), 'editread')) {
                return '您无权编辑！';
            }

            $readdata = $_G['TABLE']['READ']->getData($postarray['id']);
            if (!$readdata) {
                return '未找到该帖！';
            }

            if (!(($readdata['uid'] && $readdata['uid'] == $_G['USER']['ID']) || $admin || $bkadmin)) {
                return '您无权管理该文章！';
            }

            /*
            //检查字段
            $cols = $_G['TABLE']['READ'] -> getColumns();
            foreach ($postarray as $key => $value) {
            if (!$cols[$key]) {
            unset($postarray[$key]);
            }
            }
             */

            // 记录被编辑时间
            $postarray['lastedituid']  = $_G['USER']['ID'];
            $postarray['lastedittime'] = time();

            if (!$postarray['del']) {
                if (!($_G['TABLE']['READ']->newData($postarray))) {
                    return sqlError();
                }
                $rid = $postarray['id'];
            } else {
                foreach ($postarray as $k => $v) {
                    $readdata[$k] = $v;
                }
                $readdata['del'] = 0;
                if (!($_G['TABLE'][1 == $postarray['del'] ? 'CYCLE' : 'AUDIT']->newData([
                    'tn'   => 'read',
                    'data' => json_encode($readdata, 320),
                    'time' => time(),
                ]))) {
                    return sqlError();
                }
                $_G['TABLE']['READ']->delData($postarray['id']);
                $rid = $_G['TABLE'][1 == $postarray['del'] ? 'CYCLE' : 'AUDIT']->getId();
            }

            //if ($mc) {
            return $rid;
            //} else {
            //    return TRUE;
            //    header("Location:index.php?c=read&id={$postarray['id']}&page=1");
            //}
        } else {
            //===============================发布文章==============================
            if (!InArray(getUserQX(), 'postread')) {
                if (!$_G['USER']['ID']) {
                    return '请<a class="pk-text-primary pk-hover-underline" href="' . ReWriteURL('login', '', 'referer=' . urlencode($_G['SYSTEM']['LOCATION'])) . '">登录</a>后再操作';
                }
                return '您无权发帖！';
            }

            $readsortdata = $_G['TABLE']['READSORT']->getData(Cnum($postarray['sortid']));

            if ($readsortdata['banpostread']) {
                return '该版块禁止发布文章';
            }

            if (!chkReadSortQx($postarray['sortid'])) {
                return '您的权限不足以在该版块发帖';
            }

            if (!$postarray['uid']) {
                $postarray['uid'] = $_G['USER']['ID'];
            }
            $postreadjifen = Cnum($readsortdata['postreadjifen']);
            if (!$postreadjifen) {
                $postreadjifen = Cnum($_G['SET']['POSTREADJIFEN']);
            }
            $postreadtiandou = Cnum($readsortdata['postreadtiandou']);
            if (!$postreadtiandou) {
                $postreadtiandou = Cnum($_G['SET']['POSTREADTIANDOU']);
            }
            if (($postreadjifen < 0 && $_G['USER']['JIFEN'] + $postreadjifen < 0) || ($postreadtiandou < 0 && $_G['USER']['TIANDOU'] + $postreadtiandou < 0)) {
                return "您的积分不足无法发帖，发帖" . ($postreadtiandou < 0 ? '' : '+') . "{$postreadtiandou}{$_G['SET']['TIANDOUNAME']}，" . ($postreadjifen < 0 ? '' : '+') . "{$postreadjifen}{$_G['SET']['JIFENNAME']}";
            }

            if (!$postarray['postip']) {
                $postarray['postip'] = getClientInfos('ip');
            }
            if (!$postarray['posttime']) {
                $postarray['posttime'] = time();
            }
            if (!$postarray['activetime']) {
                $postarray['activetime'] = time();
            }

            if (!$postarray['del']) {
                if (!($_G['TABLE']['READ']->newData($postarray))) {
                    return sqlError();
                }
                $newid = $_G['TABLE']['READ']->getId();
            } else {
                $newData        = $postarray;
                $newData['del'] = 0;
                if (!($_G['TABLE'][1 == $postarray['del'] ? 'CYCLE' : 'AUDIT']->newData([
                    'tn'   => 'read',
                    'data' => json_encode($newData, 320),
                    'time' => time(),
                ]))) {
                    return sqlError();
                }
                $newid = $_G['TABLE'][1 == $postarray['del'] ? 'CYCLE' : 'AUDIT']->getId();
            }

            if (((($postreadjifen < 0 || $postreadtiandou < 0) && $postarray['del']) || !$postarray['del']) && $_G['USER']['ID']) {
                UserDataChange(array('jifen' => $postreadjifen, 'tiandou' => $postreadtiandou), false, '+', '发布文章');
            }
            //if ($mc) {
            return $newid;
            //} else {
            //    return TRUE;
            //    header("Location:index.php?c=read&id={$newid}&page=1");
            //}
        }
    } elseif ('reply' == $type || 'reply_reply' == $type) {
        //===========================回复发布及编辑=================================
        if (!$postarray['content']) {
            $postarray['content'] = newBBcode(trim($_POST['content']), 'reply', null, null, false);
        }
        if (!str_replace([' ', '&nbsp;'], '', $postarray['content'])) {
            return '内容不能为空';
        }
        $reply_strlen = mb_strlen($postarray['content']);
        $reply_minlen = Cnum($_G['SET']['REPLYCONTENTMIN'], 0, true, 0);
        $reply_maxlen = Cnum($_G['SET']['REPLYCONTENTMAX'], 0, true, 0);
        if ($reply_minlen && $reply_strlen < $reply_minlen) {
            return "回复字数不能少于{$reply_minlen}个字";
        }
        if ($reply_maxlen && $reply_strlen > $reply_maxlen) {
            return "回复字数不能多于{$reply_maxlen}个字";
        }

        if ($postarray['id']) {
            //==========================编辑回复====================================
            if (!InArray(getUserQX(), 'editreply')) {
                return '您无权编辑！';
            }

            $replydata = $_G['TABLE'][strtoupper($type)]->getData($postarray['id']);
            if (!$replydata) {
                return '未找到该帖！';
            }

            if (!(($replydata['uid'] && $replydata['uid'] == $_G['USER']['ID']) || $admin || $bkadmin)) {
                return '您无权管理该回复！';
            }

            if (!$postarray['del']) {
                if (!($_G['TABLE'][strtoupper($type)]->newData($postarray))) {
                    return sqlError();
                }
            } else {
                foreach ($postarray as $k => $v) {
                    $replydata[$k] = $v;
                }
                $replydata['del'] = 0;
                if (!($_G['TABLE'][1 == $postarray['del'] ? 'CYCLE' : 'AUDIT']->newData([
                    'tn'   => $type,
                    'data' => json_encode($replydata, 320),
                    'time' => time(),
                ]))) {
                    return sqlError();
                }
                $_G['TABLE'][strtoupper($type)]->delData($postarray['id']);
            }

            //if ($mc) {
            return $replydata['rid'];
            //} else {
            //    return TRUE;
            //    header("Location:index.php?c=read&id={$replydata['rid']}&page=1");
            //}
        } else {
            //==========================发布回复====================================
            if (!$postarray['rid']) {
                $postarray['rid'] = Cnum($_POST['rid'], false, true, 1);
            }

            if (!InArray(getUserQX(), 'postreply')) {
                if ($_G['USER']['ID']) {
                    return '您无权回复，具体请联系管理员';
                } else {
                    return '请<a class="pk-text-primary pk-hover-underline" href="' . ReWriteURL('login', '', 'referer=' . urlencode($_G['SYSTEM']['LOCATION'])) . '">登录</a>后再操作';
                }
            }
            if ('reply_reply' == $type) {
                $replydata    = $_G['TABLE']['REPLY']->getData($postarray['rid']);
                $readdata     = $_G['TABLE']['READ']->getData($replydata['rid']);
                $readsortdata = $_G['TABLE']['READSORT']->getData($readdata['sortid']);
            } else {
                $readdata     = $_G['TABLE']['READ']->getData($postarray['rid']);
                $readsortdata = $_G['TABLE']['READSORT']->getData($readdata['sortid']);
            }

            if (!$readdata) {
                return '回复目标错误';
            }

            if ($readdata['locked']) {
                return '该文章已被锁定无法回复';
            }

            if (!chkReadSortQx($readdata['sortid'], 'replylevel')) {
                return '您的权限不足以在该版块回复';
            }
            $postreplyjifen = Cnum($readsortdata['postreplyjifen']);
            if (!$postreplyjifen) {
                $postreplyjifen = Cnum($_G['SET']['POSTREPLYJIFEN']);
            }
            $postreplytiandou = Cnum($readsortdata['postreplytiandou']);
            if (!$postreplytiandou) {
                $postreplytiandou = Cnum($_G['SET']['POSTREPLYTIANDOU']);
            }
            if (($postreplyjifen < 0 && $_G['USER']['JIFEN'] + $postreplyjifen < 0) || ($postreplytiandou < 0 && $_G['USER']['TIANDOU'] + $postreplytiandou < 0)) {
                return "您的积分不足无法回帖，回帖" . ($postreplytiandou < 0 ? '' : '+') . "{$postreplytiandou}{$_G['SET']['TIANDOUNAME']}，" . ($postreplyjifen < 0 ? '' : '+') . "{$postreplyjifen}{$_G['SET']['JIFENNAME']}";
            }
            if ('reply' == $type) {
                if (!$postarray['fnum']) {
                    $postarray['fnum'] = $readdata['fs'] + 1;
                }
            }
            if (!$postarray['uid']) {
                $postarray['uid'] = $_G['USER']['ID'];
            }
            if (!$postarray['postip']) {
                $postarray['postip'] = getClientInfos('ip');
            }
            if (!$postarray['posttime']) {
                $postarray['posttime'] = time();
            }

            if (!$postarray['del']) {
                if (!($_G['TABLE'][strtoupper($type)]->newData($postarray))) {
                    return sqlError();
                }
                $replyid = $_G['TABLE'][strtoupper($type)]->getId();
            } else {
                $newData        = $postarray;
                $newData['del'] = 0;
                if (!($_G['TABLE'][1 == $postarray['del'] ? 'CYCLE' : 'AUDIT']->newData([
                    'tn'   => $type,
                    'data' => json_encode($newData, 320),
                    'time' => time(),
                ]))) {
                    return sqlError();
                }
                $replyid = 0;
            }
            $array = [];
            if ('reply' == $type) {
                $array['fs'] = $readdata['fs'] + 1;
                if ($replyid) {
                    $array['replyid'] = $replyid;
                }
            } else {
                table('reply')->update([
                    'id'         => $replydata['id'],
                    'replycount' => ['+', 1],
                ]);
            }
            $array['id']         = $readdata['id'];
            $array['activetime'] = time();
            $_G['TABLE']['READ']->newData($array);

            if (((($postreplyjifen < 0 || $postreplytiandou < 0) && $postarray['del']) || !$postarray['del']) && $_G['USER']['ID']) {
                UserDataChange(array('jifen' => $postreplyjifen, 'tiandou' => $postreplytiandou), false, '+', '发布回复');
            }

            //通知被回复的作者和人员
            $tzbl    = false;
            $httpurl = 'http' . ('on' == $_SERVER['HTTPS'] ? 's' : '') . "://{$_G['SYSTEM']['DOMAIN']}/";
            $readurl = ReWriteURL('read', "id={$readdata['id']}&page=1");
            $userurl = ReWriteURL('center', "uid=" . user('id'));
            $notice  = function ($msg, $http = '') {
                return str_replace('[HTTP]', $http, $msg);
            };
            // @的人
            $atuid = 0;
            if (substr($postarray['content'], 0, 1) == '@') {
                $epos = strpos($postarray['content'], ':');
                if ($epos) {
                    $atuid = substr($postarray['content'], 1, $epos - 1);
                }
            }
            // 楼中楼的回复通知
            if ('reply_reply' == $type && !$atuid && user('id') != $replydata['uid']) {
                $tzbl = true;
                $msg  = '您在<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $readurl . '">' . $readdata['title'] . '</a>文章的第' . $replydata['fnum'] . '楼的回复收到了来自<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $userurl . '">' . user('username') . '</a>的新回应，快去看看吧~';
                NewMessage($replydata['uid'], $notice($msg), 0, 2);
                if (function_exists('sendmail') && set('app_systememail_replysendemail')) {
                    $email = table('user')->where($replydata['uid'])->find('email');
                    sendmail($email, set('logotext') . '-您的回复收到了新回应', $notice($msg, $httpurl));
                }
            }
            // @的回复通知
            if (!$tzbl && $atuid && user('id') != $atuid) {
                $tzbl = true;
                if ('reply_reply' == $type) {
                    $msg = '您在<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $readurl . '">' . $readdata['title'] . '</a>文章的第' . $replydata['fnum'] . '楼的楼中楼回复收到了来自<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $userurl . '">' . user('username') . '</a>的新回应，快去看看吧~';
                } else {
                    $msg = '您在<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $readurl . '">' . $readdata['title'] . '</a>文章的回复收到了来自第' . $postarray['fnum'] . '楼的<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $userurl . '">' . user('username') . '</a>的新回复，快去看看吧~';
                }
                NewMessage($atuid, $notice($msg), 0, 2);
                if (function_exists('sendmail') && set('app_systememail_replysendemail')) {
                    $email = table('user')->where($atuid)->find('email');
                    sendmail($email, set('logotext') . '-您的回复收到了新回复', $notice($msg, $httpurl));
                }
            }
            // 一般回复通知
            if (!$tzbl && user('id') != $readdata['uid'] && !$atuid) {
                $tzbl = true;
                $msg  = '您的文章<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $readurl . '">' . $readdata['title'] . '</a>收到了来自第' . $postarray['fnum'] . '楼<a target="_blank" class="pk-text-primary pk-hover-underline" href="[HTTP]' . $userurl . '">' . user('username') . '</a>的新回复，快去看看吧~';
                NewMessage($readdata['uid'], $notice($msg), 0, 2);
                if (function_exists('sendmail') && set('app_systememail_replysendemail')) {
                    $email = table('user')->where($readdata['uid'])->find('email');
                    sendmail($email, set('logotext') . '-您的文章收到了新回复', $notice($msg, $httpurl));
                }
            }

            return $postarray['rid'];
        }
    }
}

function chkReadSortQx($sortid, $qx = 'postlevel')
{
    $sortid = Cnum($sortid, false, true, 1);
    if (!$sortid) {
        return true;
    }
    // 获取用户阅读权限
    $readlevel = Cnum(getUserQX(false, 'readlevel'), 0);
    $sortdata  = table('readsort')->where($sortid)->find();
    if (!$sortdata) {
        return true;
    }
    // 检测阅读权限
    if ($readlevel < $sortdata[$qx]) {
        return false;
    }
    //检测是否是允许的用户组
    if ($sortdata['allowgroupids'] && !InArray($sortdata['allowgroupids'], user('groupid'))) {
        return false;
    }
    return true;
}

//获取版块动态、发帖、回复数
function getReadCount($sortid, $type = 'count', $count = 0)
{
    global $_G;
    if ('count' == $type) {
        if ($sortid) {
            $sql = array('sortid' => $sortid, 'del' => false);
        } else {
            $sql = array('del' => false);
        }
    } elseif ('today' == $type) {
        if ($sortid) {
            $sql = 'where `del`=false and `sortid`=' . $sortid . ' and  `posttime`>' . strtotime(date('Y-m-d 00:00:00', time())) . ' and `posttime`<' . strtotime(date('Y-m-d 23:59:59', time()));
        } else {
            $sql = 'where `del`=false and  `posttime`>' . strtotime(date('Y-m-d 00:00:00', time())) . ' and `posttime`<' . strtotime(date('Y-m-d 23:59:59', time()));
        }
    } else {
        return 0;
    }
    $count = $_G['TABLE']['READ']->getCount($sql) + $count;
    if ($sortid) {
        $zbk = $_G['TABLE']['READSORT']->getDatas(0, 0, "where `pid`='{$sortid}' and id<>'{$sortid}'");
        if ($zbk) {
            foreach ($zbk as $value) {
                $count = getReadCount($value['id'], $type, $count);
            }
        }
    }
    return $count;
}

//检测用户是否具有指定权限
function getUserQX($uid = false, $zd = 'quanxian')
{
    global $_G;
    if (false === $uid || $uid == $_G['USER']['ID']) {
        $uid           = $_G['USER']['ID'];
        $userdata      = $_G['USER'];
        $usergroupdata = $_G['USERGROUP'];
        $zd            = strtoupper($zd);
    } else {
        $userdata      = $_G['TABLE']['USER']->getData(Cnum($uid));
        $usergroupdata = $userdata['groupid'] ? $_G['TABLE']['USERGROUP']->getData($userdata['groupid']) : false;
    }
    if ($usergroupdata) {
        //用户组为主
        if ('readlevel' == $zd && $usergroupdata['readlevelmax']) {
            return ($usergroupdata['readlevel'] < $userdata['readlevel'] ? $userdata['readlevel'] : $usergroupdata['readlevel']);
        }
        return $usergroupdata[$zd];
    } else {
        //用户个人权限次之
        return $userdata[$zd];
    }
}

//用户附件检测函数
function OrderDownloadAttachment(array $array)
{
    global $_G;
    if (!$array['uid']) {
        $array['uid'] = $_G['USER']['ID'];
    }
    if (Cnum($array['attachmentid'], false, true, 1)) {
        $array['attachmentdata'] = $_G['TABLE']['UPLOAD']->getData($array['attachmentid']);
    }
    if (!$array['attachmentdata']) {
        return false;
    }
    $data = $array['attachmentdata']['downloadeduids'];
    if (!$data) {
        return false;
    }
    if (Cnum($_G['SET']['ATTACHMENTTIMEOUT'], false, true, 1) || json_decode($data)) {
        //新版，具有超时监控
        $data = JsonData($data, 'uid_' . $array['uid']);
        if ($data) {
            //下载过
            if (Cnum($_G['SET']['ATTACHMENTTIMEOUT'], false, true, 1)) {
                if (time() - Cnum($data) > $_G['SET']['ATTACHMENTTIMEOUT']) {
                    //超时了
                    return false;
                } else {
                    //未超时
                    return true;
                }
            } else {
                //无超时限制
                return true;
            }
        } else {
            //未下载过
            return false;
        }
    } else {
        //旧版
        if (strpos($data, "_{$array['uid']}_") === false) {
            //未下载过
            return false;
        } else {
            //下载过
            return true;
        }
    }
}

function SaveDownloadRecord(array $array)
{
    global $_G;
    if (!$array['uid']) {
        $array['uid'] = $_G['USER']['ID'];
    }
    if (Cnum($array['attachmentid'], false, true, 1)) {
        $array['attachmentdata'] = $_G['TABLE']['UPLOAD']->getData($array['attachmentid']);
    }
    if (!$array['attachmentdata']) {
        return false;
    }
    $data = $array['attachmentdata']['downloadeduids'];
    $data = JsonData($data, 'uid_' . $array['uid'], time());
    return $data;
}

function sendCloudSms($phone, $code)
{
    if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
        return '手机号不正确';
    }
    if (!$code && 0 != $code) {
        return '验证码不正确';
    }
    global $_G;
    // 手机号
    $phonenumber = $phone;
    //请求发送短信
    $_apiurl = "https://www.hadsky.com/index.php?c=app&a=zhanzhang:index3&s=sendsms&domain={$_G['SYSTEM']['DOMAIN']}&code={$code}&phonenumber={$phonenumber}&signname={$_G['SET']['APP_PUYUETIAN_SMS_SIGNNAME']}&sitekey=" . md5($_G['SET']['APP_HADSKYCLOUDSERVER_SITEKEY'] . $_G['SYSTEM']['DOMAIN']);
    $r       = json_decode(GetPostData($_apiurl, '', 10), true);
    //记录发送记录
    $_G['TABLE']['APP_PUYUETIAN_SMS_RECORD']->newData(array('pn' => $phonenumber, 'ip' => getClientInfos('ip'), 'state' => $r['state'], 'msg' => $r['msg'], 'code' => $code, 'date' => date('Ymd'), 'datetime' => date('Y-m-d H:i:s')));
    if ('ok' == $r['state']) {
        return true;
    }
    return $r['msg'] ? $r['msg'] : '发送失败';
}

function forumList($pid = 0, $only_field = false, $show_hide = true)
{
    $get_forum_datas = function ($where, $select, $forum_datas, $me, $n) {
        $select_where = function ($where, $select) {
            $rs = [];
            foreach ($select as $data) {
                $is = true;
                foreach ($where as $k => $v) {
                    if ($data[$k] != $v) {
                        $is = false;
                    }
                }
                if ($is) {
                    $rs[] = $data;
                }
            }
            return $rs;
        };
        $forum_title = function ($n, $last) {
            $str = '';
            for ($i = 0; $i < $n; $i++) {
                if ($i == $n - 1) {
                    $str .= '&nbsp;' . ($last ? '└' : '├') . '&nbsp;';
                } else {
                    $str .= '&nbsp;│';
                }
            }
            return $str;
        };
        $datas = $select_where($where, $select);
        foreach ($datas as $k => $v) {
            $last = true;
            if (isset($datas[$k + 1]) && $datas[$k + 1]['pid'] == $v['pid']) {
                $last = false;
            }
            $v['_title']   = $forum_title($n, $last) . $v['title'];
            $forum_datas[] = $v;
            $where['pid']  = $v['id'];
            $forum_datas   = $me($where, $select, $forum_datas, $me, $n + 1);
        }
        return $forum_datas;
    };
    $where = [
        'pid' => $pid,
    ];
    if (!$show_hide) {
        $where['show'] = 1;
    }
    $forum_select = table('readsort')->order('rank asc')->select();
    $forum_datas  = $get_forum_datas($where, $forum_select, [], $get_forum_datas, 0);
    if ($only_field) {
        if (is_string($only_field)) {
            $only_field = explode(',', $only_field);
        }
        foreach ($only_field as $field) {
            foreach ($forum_datas as $k => $v) {
                if ($k != $field) {
                    unset($forum_datas[$k]);
                }
            }
        }
    }
    return $forum_datas;
}

/**
 * 因性能问题该函数已弃用，请使用上面的函数
 */
function __forumList($pid = 0, $only_field = false, $show_hide = true)
{
    temp('forum_data', []);
    temp('forum_cnum', 0);
    temp('forum_select', table('readsort')->order('rank asc')->select());
    temp('forum_select_where', function ($where) {
        $datas = temp('forum_select');
        $rs    = [];
        foreach ($datas as $data) {
            $is = true;
            foreach ($where as $k => $v) {
                if ($data[$k] != $v) {
                    $is = false;
                }
            }
            if ($is) {
                $rs[] = $data;
            }
        }
        return $rs;
    });
    temp('_bbs_forum_list_cnum', function ($n, $last = false) {
        $str = '';
        for ($i = 0; $i < $n; $i++) {
            if ($i == $n - 1) {
                $str .= '&nbsp;' . ($last ? '└' : '├') . '&nbsp;';
            } else {
                $str .= '&nbsp;│';
            }
        }
        return $str;
    });
    temp('_bbs_forum_list_list', function ($pid, $r = false, $show_hide = true) {
        $where = [
            'pid' => $pid,
        ];
        if (!$show_hide) {
            $where['show'] = 1;
        }
        $data = temp('forum_select_where')($where);
        if (!$data) {
            return false;
        }
        if ($r) {
            return true;
        }
        foreach ($data as $k => $v) {
            $forum_data   = temp('forum_data');
            $v['_level']  = temp('forum_cnum');
            $v['_title']  = temp('_bbs_forum_list_cnum')(temp('forum_cnum'), count($data) - 1 == $k) . $v['title'];
            $forum_data[] = $v;
            temp('forum_data', $forum_data);
            if (temp('_bbs_forum_list_list')($v['id'], true, $show_hide)) {
                temp('forum_cnum', temp('forum_cnum') + 1);
                temp('_bbs_forum_list_list')($v['id'], false, $show_hide);
            } elseif (count($data) - 1 == $k) {
                temp('forum_cnum', temp('forum_cnum') - 1);
            }
            if (!$v['pid']) {
                temp('forum_cnum', 0);
            }
        }
        return temp('forum_data');
    });
    $data = temp('_bbs_forum_list_list')($pid, false, $show_hide);
    if ($only_field && $data) {
        $_data = [];
        foreach ($data as $k => $v) {
            $_data[] = $v[$only_field];
        }
        $data = $_data;
    }
    if (!$data) {
        return [];
    }
    $data = arrKeyToLower($data);
    return $data;
}

function userTitle($user)
{
    $jifen = 0;
    $name  = '';
    if (cnum($user)) {
        $jifen = $user;
    } elseif (is_array($user)) {
        $jifen = $user['jifen'];
    } elseif (strpos($user, 'uid:') !== false) {
        $uid   = str_replace('uid:', '', $user);
        $jifen = table('user')->where($uid)->find('jifen');
    }
    if (!set('jifentitle')) {
        return cnum($jifen / 100) . '级';
    }
    $jingyan_levels = explode(',', set('jifentitle'));
    foreach ($jingyan_levels as $level) {
        $level = explode('|', $level);
        if ($jifen >= $level[0]) {
            $name = $level[1];
        }
    }
    return $name;
}

function atData($name)
{
    $data = [];
    foreach (set() as $k => $v) {
        if (strpos($k, $name) === 0) {
            $data[$k] = $v;
        }
    }
    return $data;
}

function medalData($id, $type = 'all')
{
    $md   = set('medaldata');
    $null = 'all' == $type ? [] : '';
    if (!$md) {
        return $null;
    }
    $md   = explode(',', $md);
    $data = [];
    foreach ($md as $v) {
        $v = explode('|', $v);
        if ($v[0] == $id) {
            $data = [
                'id'    => $v[0],
                'title' => $v[1],
                'image' => $v[2],
            ];
            break;
        }
    }
    if (!$data) {
        return $null;
    }
    if ('all' == $type) {
        return $data;
    }
    return $data[$type];
}
