<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class PublishAction extends AuthorAction
{
    public function run()
    {
        $chapter = $this->getController()->getChapter();
        $drafts = $this->db()->select()->from(Draft::table())->where(array('authorid'=>$this->getAuthorId(),'chapterid'=>$chapter['chapterid'],'deleted'=>0))->asc('sort')->find();
    	if (empty($drafts))
    	{
    		throw new iSystemException('您的章节里没有续传内容，不能发布');
    	}
        
    	foreach ($drafts as $draft)
    	{
    		$content[] = $draft['content'];
    	}
    	$data = array(
            'content' => $this->saveAnalyze(implode("\n", $content)),
            'display' => 1,
        );
        Chapter::single()->update($chapter['chapterid'], $chapter['bookid'], $data);
    
    	$this->db()->update(Draft::table())->value(array('status'=>1))->where(array('chapterid'=>$chapter['chapterid'],'authorid'=>$this->getAuthorId(),'deleted'=>0))->q();
    
    	$chaptername = $chapter['chaptername'];

    	if (!$chapter['updatedate'])
    	{
    	    $this->db()->update(Book::table())->value(array('lastchaptername' => $chaptername, 'lastchapterid' => $chapter['chapterid'], 'updatedate' => CDATETIME))->where('bookid='.S::sqlEscape($chapter['bookid']))->q();
    	}
    	$message[] = '章节《'.$chaptername.'》发布成功';
    	$message[] = ilink('点击察看效果', $this->getController()->url('read',array('bid'=>$chapter['bookid'],'cid'=>$chapter['chapterid'])));
    	$message[] = '返回'.ilink('章节列表',$this->getController()->url('system',array('s'=>'author','c'=>'chapter','bid'=>$chapter['bookid']))).'<br/>'.ilink('续传列表', $this->getController()->url('system',array('s'=>'author','c'=>'draft','cid'=>$chapter['chapterid']))).'.'.ilink('作者中心', $this->getController()->url('system',array('s'=>'author')));
    	$this->showMessage($message);
    }
}