<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class EditAction extends MemberAction
{
    public function run()
    {
        $id = S::gp('id','G',2);
        $sql = 'SELECT d.*,dd.content FROM '.Diary::table().' AS d INNER JOIN '.DiaryData::table().' AS dd ON d.id = dd.did WHERE d.id = '.S::sqlEscape($id);
        $diary = $this->db()->setQueryString($sql)->find(true);
        if (empty($diary))
        {
            throw new iSystemException('不存在的日志');
        }
        
        if (isset($_POST['content']))
        {
            $subject = S::gp('subject','P');
            $content = S::gp('content','P');
            $type = S::gp('type','P',2);
            $privacy = S::gp('privacy','P',2);
            $password = S::gp('password','P');
            $abstract = S::gp('abstract','P');
            $toped = S::gp('toped','P',2);
            $comment = S::gp('comment','P',2);
            
            if ($password && 10 < mb_strlen($password,'utf-8'))
            {
                throw new iSystemException('访问密码不能大于10个字');
            }
            if (empty($subject) || 8 > mb_strlen($subject,'utf-8') || 150 < mb_strlen($subject,'utf-8'))
            {
                throw new iSystemException('标题长度不能小于8个字或者大于150个字');
            }
            if (empty($content))
            {
                throw new iSystemException('请输入日志内容');
            }
            if ($abstract && 200 < mb_strlen($abstract,'utf-8'))
            {
                throw new iSystemException('摘要长度不能大于200个字');
            }
            if (!$abstract)
            {
                $abstract = mb_substr($content, 0, 50, 'utf-8');
            }
            $data = array(
                'uid' => $this->uid(),
                'tid' => $type,
                'privacy' => $privacy,
                'subject' => $subject,
                'abstract' => $abstract,
                'password' => $password,
                'istoped' => $toped,
                'iscomment' => $comment,
                'createdate' => CTIME,
            );
            $this->db()->update(Diary::table())->value($data)->where('id='.S::sqlEscape($id))->q();
            $this->db()->update(DiaryData::table())->value(array('content'=>$content))->where('did='.S::sqlEscape($id))->q();
            iforward(url('system',array('s'=>'member','c'=>'diary','a'=>'read','id'=>$id)));
        }
        
        $typeList = $this->db()->select()->from(DiaryType::table())->where('uid='.S::sqlEscape($this->uid()))->find();
        $this->getController()->render('edit', array(
        		'id' => $id,
                'diary' => $diary,
                'typeList' => $typeList,
            )
        );
    }
}