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

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

if (empty($_GET['bid']))
{
    Header("HTTP/1.0 404 Not Found");
}

$bookid = S::gp('bid', 'G', 2);
$book = fetchBookInfo($bookid);
if (empty($book))
{
    iexit('不存在的小说');
}

Book::isCanRead($book['view']);

if ($_GET['sp'])
{
    $sp = S::gp('sp', 'G', 2);
    $db->update(SpecialSubjects::table())->incrField(array('click'=>1))->where(array('id'=>$sp))->q();
}

$returnurl = urlencode(rtrim(setting('basehost'), '/') . url('bookshow', array('bid'=>$bookid)));

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));
}
extract($book);

$blackNum = $book['black'];
$redNum = $book['red'];
$image = empty($book['image']) ? '' : bookCover($bookid);
$keyWords = Book::keyWordLink($book['keywords']);

$bookinfo = isWebRequest() ? $book['bookinfo'] : str_replace(array('&nbsp;',"\n", '<br/>', ' '), '', $book['bookinfo']);

$lastchapter = "<a href='".url('read', array('bid'=>$bookid, 'cid'=>$book['lastchapterid']))."'>".trim($book['lastchaptername'])."</a>";
$url = url('chapter', array('bid'=>$bookid));
$lastupdate = substr($book['updatedate'], 0, 10);

$firstChapter = array();
$chapters = Chapter::single()->getChapterList($bookid);
if (!empty($chapters))
{
    $firstChapter = $chapters[0];
}

if (isWebRequest())
{
    if (count($chapters) > 16)
    {
        $newList = array_splice($chapters, count($chapters) - 16, 16);
    }
    else
    {
        $newList = $chapters;
    }
    $newList = array_reverse($newList);

    $sql = 'SELECT bookid,bookname FROM '.Book::table().' WHERE typeid = '.$typeid.' AND view = 1 ORDER BY RAND() LIMIT 20';
    $key = md5($sql + $bookid);
    $randBooks = $cache->get($key);
    if (false === $randBooks)
    {
        $randBooks = $db->setQueryString($sql)->find();
        $cache->set($key, $randBooks, 12 * 3600);
    }
}

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

$bookforum = getBookForum($bookid);
if ($_GET['debug']) {print_r($bookforum);die;}
$postCount = $bookforum['posts'];

if ($iorange_id && !isset($_SESSION['user']['book']['read'][$bookid]))
{
    $_SESSION['user']['book']['read'][$bookid] = 1;
    $feed = '{{'.$iorange_id.'}}阅读了小说《[url='.staticUrl('bookshow',array('bid'=>$bookid)).']'.$book['bookname'].'[/url]》';
    iFeed::single()->create($feed, $iorange_id, 'book');
}

if (2 == $book['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);
    }
}
else
{
    if (!getrobot())
    {
        $db->query("UPDATE `".Book::table()."` SET `click`=`click`+1, `day` = `day` + 1, `week` = `week` + 1, `month` = `month` + 1 WHERE `bookid`='$bookid'");
    }
}

include_once tpl('bookshow');