<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class SendAction extends BaseAction
{
    public function run()
    {
        $permissions = Members::single()->getPermissions($this->uid());
        !$permissions['ispm'] && $this->_halt('您当前所在的用户组没有权限发送站内短信');
        
        if ($permissions['maxpmsend'])
        {
            $count = $this->db()->getValue('SELECT COUNT(*) FROM '.Message::table().' WHERE msgfromid='.$this->uid()." AND `date`='".date('Y-m-d')."'");
            if ($count >= $permissions['maxpmsend'])
            {
                $this->_halt('您当前所在用户组每天只能发送'.$permissions['maxpmsend'].'条短信');
            }
        }
        
        $msgto = S::gp('msgto', 'P');
        $type = S::gp('type','P');
        !in_array($type,array('username','uid')) && $this->_halt('非法操作，请返回');
        if ('username' == $type)
        {
            $msgto = $this->db()->getValue('SELECT uid FROM '.Members::table().' WHERE username='.S::sqlEscape($msgto));
            if (!$msgto)
            {
                $this->_halt('不存在的用户');
            }
        }
        else
        {
            $check = Members::single()->getNameByUid($msgto);
            if (empty($check))
            {
                $this->_halt('不存在的用户');
            }
        }
        
        if (!$msgto)
        {
            $this->_halt('请输入接收者UID或者昵称');
        }
        
        $ignore = Members::single()->getIgnore($msgto);
        if ((!empty($ignore) && is_array($ignore) && in_array($this->uid(), $ignore)) || ('{ALL}' == $ignore && !isGM($this->uid())))
        {
            $this->_halt('对方拒绝接收您的站内短信');
        }

        try
        {
            Members::sendMessage($_POST['subject'], $_POST['message'], $this->uid(), $this->userName(), $msgto);
        }
        catch (Exception $exce)
        {
            $this->showMessage($exce->getMessage());
        }

        if ($this->getController()->isWebRequest())
        {
            exit(0);
        }
        $message[] = '发送成功';
        $message[] = '返回'.ilink('信箱',url('system',array('s'=>'member','c'=>'message'))).'.'.ilink('书房',url('system',array('s'=>'member')));
        $this->showMessage($message);
    }
    
    private function _halt($message)
    {
        if ($this->getController()->isWebRequest())
        {
            die($message);
        }
        else
        {
            $this->showMessage($message);
        }
    }
}