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

$noqxtip = '请<a class=\\"pk-text-primary pk-hover-underline\\" href=\\"' . ReWriteURL('login', '', 'referer=' . urlencode(sys('location'))) . '\\">登录</a>后再操作';

if (!InArray(getUserQX(), 'lookread')) {
    PkPopup('{
        icon:2,
        shade:1,
        nomove:1,
		hideclose:1,
		content:"' . (user('id') ? '您无权查看任何文章' : $noqxtip) . '"
	}');
}

$sortid = input('get.sortid/d');
if (!chkReadSortQx($sortid, 'looklevel')) {
    PkPopup('{
        icon:2,
        shade:1,
        nomove:1,
		hideclose:1,
		content:"' . (user('id') ? '您所在的用户组阅读权限太低或自身阅读权限太低无法查看该板块内容' : $noqxtip) . '"
	}');
}

$readDb = table('read');
$type   = input('get.type/s');
$page   = Cnum(input('get.page/d'), 1, true, 1);
$limit  = Cnum(set('readlistnum'), 10, true, 1);
$label  = str_replace(['%', '\''], '', input('get.label/s'));
$order  = input('get.order/s');
if (!InArray('activetime,posttime', $order)) {
    $order = set('readlistorder');
}
if ($label) {
    $labels = array_unique(explode(',', $label));
    foreach ($labels as $value) {
        $readDb->whereOr('label', 'LIKE', "%$value%");
    }
}
if ('high' == $type) {
    $readDb->where('high', 1);
} elseif ('focus' == $type) {
    $focuslist = explode('__', trim(user('idol'), '_'));
    $readDb->where('uid', 'IN', $focuslist);
} else {
    $type = '';
}

$globaltopreadlist = [];
$topreadlist       = [];
$topreadids        = [];
if ($sortid) {
    $sortids   = $sortid;
    $forumData = table('readsort')->where($sortid)->find();
    // 是否存在该版本
    if (!$forumData) {
        // 不存在该版本，显示404
        if (404 == set('deletedreadshowtype')) {
            header('HTTP/1.1 404 Not Found');
            header('status: 404 Not Found');
            set([
                'webtitle'       => '404 Not Found',
                'webkeywords'    => '',
                'webdescription' => '',
            ]);
            g('htmlcode.main', template('error', true));
            template(g('template.main'));
            exit;
        }
        PkPopup('{
            icon:0,
            shade:1,
            nomove:1,
            hideclose:1,
            content:"不存在的版块",
            close:function(){
                location.href="index.php"
            }
        }');
    }
    // 是否设置了版块跳转
    if ($forumData['url']) {
        ExitGourl($forumData['url']);
    }
    // 是否设置了显示子版块文章功能
    if ($forumData['showchildlist']) {
        $forumchildids = table('readsort')->where('pid', $sortid)->field('id')->select();
        foreach ($forumchildids as $value) {
            $sortids .= ',' . $value['id'];
        }
    }
    $readDb->where('sortid', 'IN', $sortids);
    if (1 == $page) {
        // 版块置顶的文章
        $topreadlist = table('read')->where([
            'sortid' => $sortid,
            'top'    => 1,
        ])->order('id desc')->select();
        foreach ($topreadlist as $v) {
            $topreadids[] = $v['id'];
        }
        // 全局置顶的文章
        $globaltopreadids = trim(preg_replace('/[,]+/', ',', set('globaltopreadids')), ',');
        if ($globaltopreadids) {
            $sqlOrder          = "FIELD(id,{$globaltopreadids})";
            $globaltopreadlist = table('read')->where('id', 'IN', $globaltopreadids)->order($sqlOrder)->select();
            foreach ($globaltopreadlist as $k => $v) {
                $globaltopreadlist[$k]['top'] = 1;
                $topreadids[]                 = $v['id'];
            }
        }
    }
} else {
    // 指定显示和隐藏的版块
    if (set('readlistshowbks')) {
        $readDb->where('sortid', 'IN', set('readlistshowbks'));
    } elseif (set('readlisthiddenbks')) {
        $readDb->where('sortid', 'NOT IN', set('readlisthiddenbks'));
    }
    // 动态页置顶的文章
    $activetopreadids = trim(preg_replace('/[,]+/', ',', set('activetopreadids')), ',');
    if (1 == $page && $activetopreadids) {
        $sqlOrder    = "FIELD(id,{$activetopreadids})";
        $topreadlist = table('read')->where('id', 'IN', $activetopreadids)->order($sqlOrder)->select();
        foreach ($topreadlist as $k => $v) {
            $topreadlist[$k]['top'] = 1;
            $topreadids[]           = $v['id'];
        }
    }
}
// 组装数据
// $readpage = ceil(table('read')->setQuery($readDb->getQuery())->count() / $limit);
$readDb->page($page, $limit)->order("`$order` DESC,`id` DESC");
// print_r($readDb->lastQuery());
// exit;
$readnormallist = $readDb->select();
if (!$sortid) {
    foreach ($readnormallist as $k => $v) {
        $readnormallist[$k]['top'] = 0;
    }
}
$is_null = false;
if (!$readnormallist) {
    $is_null = true;
}
$readlist = array_merge($globaltopreadlist, $topreadlist, $readnormallist);
if ($readlist) {
    $_topreadids = [];
    foreach ($readlist as $key => $readdata) {
        // 是否在置顶文章里面
        if (in_array($readdata['id'], $topreadids)) {
            if (in_array($readdata['id'], $_topreadids)) {
                unset($readlist[$key]);
                continue;
            } else {
                $_topreadids[] = $readdata['id'];
            }
        }
        // 该文章的版块信息
        if ($sortid) {
            $readlist[$key]['forumdata'] = $forumData;
        } else {
            $readlist[$key]['forumdata'] = table('readsort')->where($readdata['sortid'])->find();
        }
        // 显示图片
        $showmedia = true;
        // 检测是否为回复查看帖
        if ($readdata['replyafterlook']) {
            if (user('id')) {
                if (!table('reply')->where([
                    'rid' => $readdata['id'],
                    'uid' => user('id'),
                ])->find()) {
                    $showmedia                 = false;
                    $readlist[$key]['content'] = '该文章设置了回复查看，请回复后查看内容';
                }
            } else {
                $showmedia                 = false;
                $readlist[$key]['content'] = '您需要登录并回复后才可以查看该文章内容';
            }
        }
        // 部分内容回复后可见
        $readlist[$key]['content'] = preg_replace('/\<p class="PytReplylook"\>[\s\S]+?\<\/p\>/', '<p>隐藏内容</p>', $readdata['content']);
        // 检测阅读权限是否合法
        if (user('readlevel') < $readdata['readlevel']) {
            $showmedia                 = false;
            $readlist[$key]['content'] = '您的阅读权限太低无法查看该文章';
        }
        if (!chkReadSortQx($readlist[$key]['forumdata']['id'], 'readlevel')) {
            $showmedia                 = false;
            $readlist[$key]['content'] = '您的阅读权限太低或您的用户组不被允许查看该版块文章';
        }
        if ($readdata['uid']) {
            $readlist[$key]['userdata'] = table('user')->where($readdata['uid'])->find();
            if (file_exists(PK_USERHEAD_PATH . $readlist[$key]['userdata']['id'] . '.png')) {
                $readlist[$key]['userdata']['userhead'] = 'userhead/' . $readlist[$key]['userdata']['id'] . '.png';
            } else {
                $readlist[$key]['userdata']['userhead'] = 'userhead/0.png';
            }
            $readlist[$key]['usergroup'] = table('usergroup')->where($readlist[$key]['userdata']['groupid'])->find();
        } else {
            $readlist[$key]['userdata']             = JsonData(set('guestdata'));
            $readlist[$key]['userdata']['userhead'] = 'userhead/0.png';
        }
        // 是否有媒体
        $readlist[$key]['images'] = [];
        $readlist[$key]['videos'] = [];
        $readlist[$key]['audios'] = [];
        if ($showmedia) {
            if ($readdata['image']) {
                $readlist[$key]['images'] = explode(',', $readdata['image']);
            }
            if ($readdata['video']) {
                $readlist[$key]['videos'] = explode(',', $readdata['video']);
            }
            if ($readdata['audio']) {
                $readlist[$key]['audios'] = explode(',', $readdata['audio']);
            }
        }
        // 是否好友
        $readlist[$key]['is_friend'] = true;
        if (strpos(user('friends'), '_' . $readdata['uid'] . '_') === false) {
            $readlist[$key]['is_friend'] = false;
        }
        // 是否关注
        $readlist[$key]['is_idol'] = true;
        if (strpos(user('idol'), '_' . $readdata['uid'] . '_') === false) {
            $readlist[$key]['is_idol'] = false;
        }
        // 是否收藏
        $readlist[$key]['is_collect'] = true;
        if (strpos(user('collect'), '_' . $readdata['id'] . '_') === false) {
            $readlist[$key]['is_collect'] = false;
        }
    }
}

// seo优化
if ($forumData) {
    $weblabel = $forumData['label'];
    $webtitle = strip_tags($forumData['title']) . (1 != $page ? "-第{$page}页" : '');
    if (set('webaddedwords')) {
        $webtitle .= '-' . set('webaddedwords');
    }
    if ($forumData['webtitle']) {
        $webtitle = $forumData['webtitle'];
    }
    if ($forumData['webkeywords']) {
        $webkeywords = $forumData['webkeywords'];
    } else {
        if ($forumData['label']) {
            $webkeywords = $forumData['label'];
        }
    }
    if ($forumData['webdescription']) {
        $webdescription = $forumData['webdescription'];
    } else {
        if ($forumData['content']) {
            $webdescription = strip_tags($forumData['content']);
        }
    }
    set([
        'webtitle'       => $webtitle,
        'webkeywords'    => $webkeywords,
        'webdescription' => $webdescription,
    ]);
} else {
    $weblabel = set('defaultlabel');
    if ('list' != set('defaultpage')) {
        $webtitle = '动态' . (1 != $page ? "-第{$page}页" : '') . (set('webaddedwords') ? '-' . set('webaddedwords') : '');
    } else {
        $webtitle = set('webtitle') . (1 != $page ? "-第{$page}页" : '');
    }
    set('webtitle', $webtitle);
}

// 读取版块标签
$weblabels = explode(',', $weblabel);

// 上下页url
$q = '';
if ($label) {
    $q .= "&label={$label}";
}
if ($type) {
    $q .= "&type={$type}";
}
if (input('get.order/s')) {
    $q .= "&order={$order}";
}
$q && $q = substr($q, 1);
$syy     = $page - 1;
if ($syy < 1) {
    $syy = 1;
}
$syyurl = ReWriteURL('list', "sortid={$sortid}&page=" . $syy, $q);
$xyy    = $page + 1;
// if ($xyy > $readpage) {
//     $xyy = $readpage;
// }
$xyyurl = ReWriteURL('list', "sortid={$sortid}&page=" . $xyy, $q);
$varurl = ReWriteURL('list', "sortid={$sortid}&page=[page]", $q);

// label整理
$_weblabels = [];
foreach ($weblabels as $value) {
    if (!$value) {
        continue;
    }
    if (strpos(",{$label},", ",{$value},") !== false) {
        // 存在标签
        $active = true;
        $_label = trim(preg_replace('/[,]+/', ',', str_replace($value, '', $label)), ',');
    } else {
        // 不存在该标签
        $active = false;
        $_label = trim(preg_replace('/[,]+/', ',', $label . ',' . $value), ',');
    }
    if (!$q && !$sortid && set('rewriteurl')) {
        $_weblabels[] = [
            'name'   => $value,
            'url'    => 'label-' . urlencode($value) . '.html',
            'active' => $active,
        ];
    } else {
        $_weblabels[] = [
            'name'   => $value,
            'url'    => "index.php?c=list&sortid={$sortid}&page=1&type={$type}&order={$order}&label=" . urlencode($_label),
            'active' => $active,
        ];
    }
}

// 输出模板
gConcat('htmlcode.output', template('list', [
    'forumdata' => $forumData,
    'readlist'  => $readlist,
    'page'      => $page,
    'syy'       => $syy,
    'xyy'       => $xyy,
    'syyurl'    => $syyurl,
    'xyyurl'    => $xyyurl,
    'varurl'    => $varurl,
    'limit'     => $limit,
    // 'readpage'  => $readpage,
    'order'     => $order,
    'weblabels' => $_weblabels,
    'sortid'    => $sortid,
    'is_null'   => $is_null,
]));
