<?php
/**
 * 首页随机推荐原创小说
 * 原创作品1万字后即可获得首页推荐,停更时间超过7天自动撤下首页
 * * 5 * * * 
 */
require_once dirname(dirname(dirname(__FILE__))) . '/init.php';

$minSize = 10000;
$timeStr = time();
$expire = 24 * 3600 * 7;
$sql = 'SELECT bookid,updatedate FROM '.Book::table().' WHERE aliasname <> "" AND `type` = 2 AND view = 1 AND size >= '.$minSize;
$books = $db->setQueryString($sql)->find();

if (empty($books))
{
    exit(0);
}

foreach ($books as $book)
{
    $bookId = $book['bookid'];
    $update = strtotime($book['updatedate']);
    
    if (isRecommend($bookId))
    {
        // 取消推荐
        if ($timeStr - $update > $expire)
        {
            cancelRecommend($bookId);
        }
    }
    else
    {
        if ($timeStr - $update < $expire)
        {
            createRecommend($bookId);
        }
    }
}

function isRecommend($bookId)
{
    return $GLOBALS['db']->getValue('SELECT COUNT(*) FROM '.Recommend::table().' WHERE id = ' . $bookId . " AND `type` ='book'");
}

function cancelRecommend($bookId)
{
    $GLOBALS['db']->delete(Recommend::table())->where('id=' . $bookId . " AND type='book'");
    updateCommend();
}

function createRecommend($bookId)
{
    $GLOBALS['db']->insert(Recommend::table())->value(array('id' => $bookId, 'type' => 'book', 'createdate' => date('Y-m-d H:i:s')))->q();
    updateCommend();
}