<?php
/**
 * 原创作品5万字后自动设置为书管,停更时间超过1个月自动撤销书管.
 * 原创作品达到20万字可以增设一位书管.
 * 1 3 * * * 
 */
require_once dirname(dirname(dirname(__FILE__))) . '/init.php';

// 黑名单小说，在名单内的将不产生书管
$blackList = array(14708);
$maxSize = 50000;
$maxTimeStr = 24 * 3600 * 30; // 一个月
$currentTime = time();

// 找出原创书籍ID
$sql = 'SELECT bookname, bookid, b.updatedate, size, a.uid FROM '.Book::table().' AS b INNER JOIN '.Authors::table().' AS a ON a.id = b.authorid WHERE `type` = 2 AND b.view = 1';
$query = $db->query($sql);
while ($book = $db->getArr($query))
{
    $bookName = $book['bookname'];
    $bookId = $book['bookid'];

    if (in_array($bookId, $blackList))
    {
        continue;
    }
    
    $size = $book['size'];
    $bookManagers = bookHasManager($bookId);
    
    if ($size < $maxSize)
    {
        if (0 < count($bookManagers))
        {
            // 字数不够的书直接取消掉书管，防止某些人利用字数漏洞刷永久书管（先写5W字，然后删掉）
            $pm = '字数少于'.$maxSize.'，取消书管';
            foreach ($bookManagers as $uid)
            {
                deleteBookManager($bookId, $uid, $pm);
            }
        }
    }
    else
    {
        if (0 < count($bookManagers) && ($currentTime - strtotime($book['updatedate'])) > $maxTimeStr)
        {
            // 一个月没有更新过的书取消掉书管
            $pm = '一个月未更新，取消书管';
            foreach ($bookManagers as $uid)
            {
                deleteBookManager($bookId, $uid, $pm);
            }
        }
        else if (0 >= count($bookManagers) && ($currentTime - strtotime($book['updatedate'])) < $maxTimeStr)
        {
            /**
             * 没有书管且一个月内有更新的，将作者本人设置为书管
             * 不过这个会出现一种情况，就是某个作者达到字数标准后
             * 被系统设置成书管，然后被撤销，这时他可以通过乱更一章
             * 让系统重新设置他为书管，在设置完后，将乱更的内容删除
             * 达到作弊效果，为避免这种情况，每次取消了一个作者的书管权限后
             * 写一条记录，记住他被撤销的时间，一旦他被撤销
             * 那么就必须连续更新7天，每天最少一章，每章不低于2000字
			 * 达到标准后可以重新设置
             */
            addBookManager($bookId, $book['uid']);
        }
    }
}

/**
 * 小说是否设置了书管
 * 有书管返回书管UID，否则返回false
 * @param boolean $bookId
 * @return false|int
 */
function bookHasManager($bookId)
{
    $bookManagers = getBookManage($bookId);
    if (empty($bookManagers))
    {
        return array();
    }
    
    $array = array();
    foreach ($bookManagers as $manager)
    {
        $array[] = $manager['uid'];
    }
    
    return $array;
}

/**
 * 取消书管
 * @param int $bookId
 * @param int $uid
 * @param boolean $pm
 * @return void
 */
function deleteBookManager($bookId, $uid, $pm)
{
    $dateTime = date('Y-m-d H:i:s');
    $GLOBALS['db']->update(BookManagers::table())->value(array('status' => 2, 'remarks' => $pm, 'updatedate' => $dateTime, 'canceltime' => $dateTime))->where('bookid='.$bookId.' AND uid = '.$uid)->q();
    updateBookManage($bookId);
    
    $book = getBookInfo($bookId);
    $subject = '[系统消息]取消书管';
    $message = '您所在的原创小说《'.$book['bookname'].'》'.$pm.'，连续7天更新，每天更新字数不少于2000字，达到要求后系统会自动将您再此设置为书管，努力更新吧！';
    Members::sendMessage($subject, $message, 1, 'admin', $uid);
}

/**
 * 设置一个书管
 * @param int $bookId
 * @param int $uid
 * @param boolean $pm
 * @return void
 */
function addBookManager($bookId, $uid, $pm = true)
{
    $manager = $GLOBALS['db']->setQueryString('SELECT * FROM '.BookManagers::table().' WHERE bookid = '.$bookId.' AND uid = '.$uid)->find(true);
    if (!empty($manager))
    {
        // 检查有没有被撤职过，被撤职过的要检查前七天的更新情况，符合要求才更新书管
        $timeStr = 24 * 3600 * 7;
        if (!empty($manager['canceltime'])) 
        {
            // 被撤销过书管的，自撤销之日起7天内将不再处理
            if (($GLOBALS['currentTime'] - strtotime($manager['canceltime'])) < $timeStr)
            {
                return;
            }
            // 找出今天之前的7天时间
            $dateRange = getDateRange(date('Y-m-d', strtotime('-7 day')), date('Y-m-d', strtotime('-1 day')));
            $inArray = array();
            foreach ($dateRange as $value)
            {
                $inArray[] = S::sqlEscape($value);
            }
            $sql = 'SELECT `date`, `size` FROM '.Chapter::table().' WHERE display = 1 AND  `date` IN ('.implode(',', $inArray) . ')';
            $updateResult = $GLOBALS['db']->setQueryString($sql)->find();
            if (7 > count($updateResult))
            {
                // 记录不足7条的表示不符合要求，直接跳过
                return;
            }
            $i = 0;
            $skipArray = array();
            foreach ($updateResult as $update)
            {
                if ($update['size'] >= 2000 && in_array($update['date'], $dateRange) && !in_array($update['date'], $skipArray))
                {
                    $skipArray[] = $update['date'];
                    $i++;
                }
            }
            if ($i < 6)
            {
                return;
            }
        }
        
        $GLOBALS['db']->update(BookManagers::table())->value(array('status' => 1, 'updatedate' => date('Y-m-d H:i:s'), 'remarks' => '原创作者字数达标，自动设置书管'))->where('bookid = '.$bookId.' AND uid = '.$uid)->q();
    }
    else
    {
        $GLOBALS['db']->insert(BookManagers::table())->value(array('bookid' => $bookId, 'uid' => $uid, 'username' => userName($uid), 'status' => 1, 'createdate' => date('Y-m-d H:i:s'), 'remarks' => '原创作者字数达标，自动设置书管'))->q();
    }
    updateBookManage($bookId);
    
    if ($pm)
    {
        $book = getBookInfo($bookId);
        $subject = '[系统消息]增设书管';
        $message = '您原创小说《'.$book['bookname'].'》字数达到'.$GLOBALS['maxSize'].'，系统自动将您设置成本书书管！';
        Members::sendMessage($subject, $message, 1, 'admin', $uid);
    }
}

/**
 * 获取一个时间范围
 * @param string $startDate
 * @param string $endDate
 * @return array
 */
function getDateRange($startDate, $endDate)
{
    $days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
    $startMonth = date("m", strtotime($startDate));
    $startDay = date("d", strtotime($startDate));
    $startYear = date("Y", strtotime($startDate));
    $dates = array();
    for($i=0; $i<$days; $i++)
    {
        $dates[$i] = date("Y-m-d", mktime(0, 0, 0, $startMonth , ($startDay+$i), $startYear));
    }
    return $dates;
}