<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
define('IN_IORANGE', true);
include('include/init.php');
include(ROOT_PATH . 'include/ColorRead.class.php');

if (URL_REWRITE)
{
    $pathInfo = iRequest::getPathInfo();
    if (!empty($pathInfo))
    {
        preg_match('/read\\'.PATH_INFO_DEPR.'(\d+)\\'.PATH_INFO_DEPR.'(\d+)/s', $pathInfo, $match);
        $_GET['bid'] = intval($match[1]);
        $_GET['cid'] = intval($match[2]);
    }
}

$tpl = 'read';
$merge = array();
$bookid = S::gp('bid','G',2);
$totalpage = S::gp('tp','G',2);
$page = isset($_GET['page']) ? S::gp('page', 'G', 2) : 1;
$pagesize = $iorange_id != 0 ? (u('size') < 1 ? 500 : u('size')) : setting('pagesize');
$style = isset($_GET['style']) ? S::gp('style', 'G', 2) : 0;

if ($style && in_array($style, ColorRead::styles()))
{
    $tpl = 'read_color';
    $merge = array('style'=>$style);
}

if ($iorange_id && isset($_POST['message']) && u('verify'))
{
    $bookpost = BookPost::single();
    if ($bookpost->isCanPost($bookid))
    {
        $data = array(
             'uid' => $iorange_id,
             'username' => $username,
             'message' => S::gp('message', 'P'),
        );
        $bookpost->create($bookid, $data);
    }

    $bookpost->updateUser($iorange_id, $username);

    iforward(urldecode($selfurl));
}
 
$bookinfo = getBookInfo($bookid);
Book::isCanRead($bookinfo['view']);

if (empty($bookinfo))
{
    iexit('不存在的小说');
}

if (Book::isOriginal($bookinfo['type']))
{
    $isClick = getCookieValue('b'.$bookid);
    if (!$isClick)
    {
        $condition = array();
        $condition[] = 'date = '.S::sqlEscape(CDATE);
        $condition[] = 'bid='.S::sqlEscape($bookid);
        $condition[] = $iorange_id ? 'uid='.S::sqlEscape($iorange_id) : 'ip='.S::sqlEscape(ONLINE_IP);
        $condition = implode(' AND ', $condition);
        $clickCheck = $db->getValue('SELECT COUNT(*) FROM '.BookClick::table().' WHERE '.$condition);
        if (!$clickCheck)
        {
            $clickType = IS_MOBILE ? (CMOBILE ? 2 : 3) : 1;
            $db->insert(BookClick::table())->value(array('bid'=>$bookid, 'uid'=>$iorange_id,'ip'=>ONLINE_IP,'type'=>$clickType,'ua'=>$_SERVER['HTTP_USER_AGENT'],'date'=>CDATE,'createdate'=>CDATETIME))->q();
            $clickFields = array('day' => 1, 'week' => 1, 'month' => 1, 'click' => 1);
            if ($iorange_id)
            {
                $clickFields = array_merge($clickFields, array('u_click' => 1, 'u_d_click' => 1, 'u_w_click' => 1, 'u_m_click' => 1));
                if (u('verify'))
                {
                    $clickFields = array_merge($clickFields, array('u_v_click' => 1, 'u_v_d_click' => 1, 'u_v_w_click' => 1, 'u_v_m_click' => 1));
                }
            }
            $db->update(Book::table())->incrField($clickFields)->where('bookid='.S::sqlEscape($bookid))->q();
        }
        setCookieValue('b'.$bookid, 1, CTIME + 24 * 3600);
    }
}

$chapterid = S::gp('cid','G',2);
$subpage = $_GET['sp'] ? S::gp('sp', 'G', 2) : 1;
$chapterObj = Chapter::single();
$chapterCache = $chapterObj->getChapters($bookid, $chapterid);
$currentChapterPage = $chapterObj->getCurrentPage($bookid, $chapterid, 10);
$row = $chapterCache['current'];
$isOriginal = Book::isOriginal($bookinfo['type']);

if ($isOriginal && !$row['display'])
{
    iexit('作者暂时未发布此章，请等作者发布后再阅读，感谢您的支持！');
}

$chaptername = $row['chaptername'];
$chapterSize = $row['size'];

if ($bookinfo['isvip'] && $row['isvip'])
{
    isLogin();
    if ($row['size'] > 1000)
    {
        $iChapterOrder = new iChapterOrder($bookid);
        $chapterOrderTable = $iChapterOrder->getTable();
        $orderCheck = $db->getValue('SELECT COUNT(*) FROM '.$chapterOrderTable.' WHERE uid='.$iorange_id.' AND cid='.$chapterid);
        if (!$orderCheck)
        {
            iexit('VIP章节，订阅后可阅读！当前章节总共'.$row['size'].'字，订阅需要'.$iChapterOrder->getPrice($row['size']).setting('creditname'). '，'.ilink('马上订阅&gt;&gt;',url('system', array('s'=>'member','a'=>'buychapter','bid'=>$bookid,'cid'=>$chapterid))));
        }
    }
}

$offset = ($subpage - 1) * $pagesize;
$tmp = $chapterObj->getContent($bookid, $chapterid);
if (empty($tmp) || $row['isimage'])
{
    $check = $chapterObj->getOne($chapterid);
    if (empty($check))
    {
        iforward(url('bookshow',array('bid'=>$bookid)));
    }

    if (empty($tmp) || (!isWebRequest() && $row['isimage']) || (isWebRequest() && !preg_match('/\w+\.(gif|jpg)/is', $tmp)))
    {
        $reportUrl = ilink('点击报告错误', url('report', array('bid'=>$bookid,'cid'=>$chapterid)));
        $tmp = '文字版暂缺，更新员正在手打中，一般10到20分钟左右能够搞定，请稍后再访问！';
        if (isWebRequest())
        {
            $reportUrl = '<a href="javascript:void(0);" onclick="report(event, \''.$chaptername.'\');" rel="nofollow">点击报告错误</a>';
        }
        $tmp .= '如果还是没内容，请'.$reportUrl.'，收到通知后我们会第一时间修复，感谢您的支持！';
    }
}

$subtotalpage = ceil(mb_strlen($tmp, 'utf-8') / $pagesize);

if ($subpage > $subtotalpage || $subpage < 1)
{
    $url = str_replace('&amp;', '&', url('read', array('bid'=>$bookid, 'cid'=>$chapterid)));
    iforward($url);
}
$content = filter(isWebRequest() ? $tmp : mb_substr(sFilter($tmp), $offset, $pagesize, 'utf-8'));
if (isWebRequest())
{
    $tpl = 'read';
    $content = $tmp;

    $isConfused = false;
    if (!$row['isimage'])
    {
        $content = str_replace(array("\n", "　"), array("<br/>", ''), $content);

        $allowsIps = setting('allowips');
        if (setting('confused') && (empty($allowsIps) || !empty($allowsIps) && !in_array(ONLINE_IP, explode('|', $allowsIps))))
        {
            $keys = chr(14 + 18).chr(6 + 3).chr(73 - 41).chr(41 - 9).chr(79 - 70).chr(90 - 81).chr(59 - 50).chr(6 + 3).chr(61 - 29).chr(26 + 6).chr(30 - 21).chr(46 - 37).chr(82 - 73).chr(98 - 89).chr(81 - 72).chr(21 - 12).chr(13 - 4).chr(41 - 32).chr(61 - 52).chr(41 - 9).chr(77 - 45).chr(39 - 7).chr(65 - 56).chr(64 - 55).chr(46 - 37).chr(27 - 18).chr(41 - 32).chr(1 + 31).chr(41 - 9).chr(89 - 80);
            $content = str_replace(array("<br/>", '&nbsp;'), array("\n", ' '), analyzeText($content));
            $tmpArray = array_map('trim', array_filter(explode("\n", $content)));
            $cArray = array();
            foreach ($tmpArray as $t)
            {
                $cArray[] = $t;
            }
            $cArray = shuffleAssoc($cArray);

            $ic = 0;
            $spilceRandArray = array(33, 40, 23, 44, 28, 30);
            $spaceArray = array(rand(3,8), rand(20, 30));
            foreach ($cArray as $key => &$c)
            {
                $cLen = mb_strlen($c, 'utf-8');
                if ($ic == 6 || $ic == 30)
                {
                    $spilce = $cLen > 20 ?  $spilceRandArray[rand(0, count($spilceRandArray) - 1)] : 1;

                }
                $kArray[] = str_replace(array(0, 1), array("\t", " "), decbin($key));
                $ic++;
            }
            $jsCode = '<script language="javascript">document.write(\'<pre id="keys">'.implode($keys, $kArray).'</pre>\');</script>';
            $content = implode('<br/>', $cArray);
            $isConfused = true;
        }
    }
    else
    {
        if (preg_match('/\w+\.(gif|jpg)/is', $content))
        {
            $exp = explode("\n", $content);
            $images = array();
            foreach ($exp as $e)
            {
                $images[] = '<img src="/'.Chapter::getImageBaseUrl($bookid) . $e.'" alt="图片载入中..." />';
            }
            $content = implode("<br/>", $images);
        }
    }
}
if ($subpage == $subtotalpage || $subpage > $subtotalpage)
{
	$subpagearr = '';
	!isWebRequest() && $content .= '<br/>（ 电脑访问 http://www.25800.net ）';
}
else
{
    $subpagearr = ilink('下页', url('read', array_merge(array('bid'=>$bookid, 'cid'=>$chapterid, 'sp'=>($subpage + 1)), $merge)));
}

if ($subpage == '1' || $subpage < 1)
{
	$subpagearr .= '';
}
else
{
    $subpagearr .= ' '.ilink('上页', url('read', array_merge(array('bid'=>$bookid, 'cid'=>$chapterid, 'sp'=> ($subpage - 1)), $merge)));
}
$subpagearr .= '['.$subpage.'/'.$subtotalpage.']';

$next_row = $chapterCache['next'];
if (!empty($next_row))
{
    $pagearr = ilink('下章', url('read', array_merge(array('bid'=>$bookid, 'cid'=>$next_row['chapterid']), $merge)));
}

$prev_row = $chapterCache['prev'];
if (!empty($prev_row))
{
    $pagearr .= ' '.ilink('上章', url('read', array_merge(array('bid'=>$bookid, 'cid'=>$prev_row['chapterid']), $merge)));
}

$gosp = '';
if ($subtotalpage > $subpage)
{
    $gosp = '<input name="sp" type="text" size="2" format="*N" emptyok="true"/><a href="'. url('read', array_merge(array('bid'=>$bookid, 'cid'=>$chapterid), $merge)) . '&amp;sp=$(sp)">跳页</a>';
}

$isAutoProgress = false;
if ($iorange_id && u('autoprogress') && u('autoprogress') > CTIME)
{
    $bookLimit = $_IORANGE['user']['group']['booklimit'];
    if ($bookLimit >= u('bnum'))
    {
        $saveArray = array(
            'memberid' => $iorange_id,
            'bid' => $bookid,
            'cid' => $chapterid,
            'sp' => $subpage,
            'createdate' => CDATETIME
        );
        Favorites::single()->save($saveArray);
        $isAutoProgress = true;
        setCookieValue('lrb'.$iorange_id, $bookid.'|'.$chapterid.'|'.$subpage, CTIME + 2 * 3600, '/');
    }
}

$isDigest = true;
$posts = getDigestCommentByBookId($bookid);
if (empty($posts))
{
	$posts = getCommentByBookId($bookid);
	$isDigest = false;
}

if (!empty($posts))
{
	foreach ($posts as $post)
	{
		$post['message'] = sFilter(preg_replace('/\[[a-z]{3}=\d+\]/i', '', $post['message']));
		$comments[] = $post;
	}
}
$bookforum = getBookForum($bookid);
$postCount = $bookforum['posts'];

$denyIps = setting('denpyips');
$xc = setting('xc');
if (!empty($denyIps) && !empty($xc))
{
    $denyIps = explode('|', $denyIps);
    if (in_array(ONLINE_IP, $denyIps))
    {
        $cLen = mb_strlen($content, 'utf-8');
        $xcLen = mb_strlen($xc, 'utf-8');
        if ($cLen > $xcLen)
        {
            $num = ceil($cLen / $xcLen);
            $content = '';
            for ($i = 0; $i < $num; $i++)
            {
                $content .= $xc . '<br/>';
            }
        }
    }
}

$originalCommends = $originalUpdateList = array();
$originalBooks = getOriginalBooks();
if ($originalBooks)
{
    shuffle($originalBooks);
    $list = array_splice($originalBooks, 0, 5);
    foreach ($list as $oBid)
    {
        $oBook = getBookInfo($oBid);
        if ($oBook)
        {
            $originalCommends[] = array('bookid' => $oBook['bookid'], 'bookname' => (!empty($oBook['aliasname']) ? $oBook['aliasname'] : $oBook['bookname']), 'author' => $oBook['author']);
        }
    }
}
$updateList = getOriginalUpdate();
if ($updateList)
{
    foreach ($updateList as $item)
    {
        if ($item['size'] > 200)
        {
            $originalUpdateList[] = array('bookid' => $item['bookid'], 'bookname' => '《'.$item['bookname'].'》于'.time2Units(strtotime($item['updatedate'])).'前更新了'.$item['size'].'字', 'author' => $item['author']);
        }
    }

    $uCount = count($originalUpdateList);
    if ($uCount >= 3)
    {
        $originalUpdateList = array_splice($originalUpdateList, 0, 3);
    }
    $originalCommends = array_splice($originalCommends, 0, 5 - $uCount);
}

include_once tpl($tpl);