<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class FavoriteAction extends BbsAction
{
    public function run()
    {
        $this->getController()->isLogin();

        $tid = S::gp('tid', 'G', 2);
        $thread = $this->getExistsThread($tid);
        $permissions = Members::single()->getPermissions($this->uid());
        $fLimit = $permissions['threadfavoritelimit'];

        if ($thread['uid'] == $this->uid())
        {
            throw new iSystemException('不能收藏自己的贴');
        }
        
        $check = $this->db()->getValue('SELECT COUNT(*) FROM '.Ufavorites::table().' WHERE uid='.S::sqlEscape($this->uid()).' AND `type`='.S::sqlEscape('thread').' AND id='.S::sqlEscape($thread['id']));
        if ($check)
        {
            throw new iSystemException('您已经收藏过这个帖子');
        }

        $count = $this->db()->getValue('SELECT COUNT(*) FROM '.Ufavorites::table().' WHERE uid='.S::sqlEscape($this->uid()).' AND `type`='.S::sqlEscape('thread'));
        if ($fLimit <= $count)
        {
            throw new iSystemException('您当前等级只能收藏'.$fLimit.'个帖子');
        }

        $this->db()->insert(Ufavorites::table())->value(array('id'=>$thread['id'],'type'=>'thread','createdate'=>CTIME,'uid'=>$this->uid()))->q();
        $this->db()->update(Threads::table())->value(array('favors'=>($thread['favors'] + 1)))->where(array('id'=>$thread['id']))->q();

        $feed = '{{'.$this->uid().'}}收藏了帖子[url='.staticUrl('system',array('s'=>'bbs','a'=>'thread','tid'=>$thread['id'])).']《'.$this->getController()->filter($thread['subject']).'》[/url]';
        iFeed::single()->create($feed, $this->uid());

        $message[] = '帖子收藏成功';
        $message[] = '返回'.ilink('帖子', url('system', array('s'=>'bbs','a'=>'thread','tid'=>$thread['id']))).'.'.ilink('版块', url('system', array('s'=>'bbs','a'=>'forum','fid'=>$thread['fid']))).'.'.ilink('社区', url('system', array('s'=>'bbs')));
        $this->showMessage($message);
    }
}