<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
class RegisterAction extends MemberAction
{
    public function run()
    {
        !setting('register') && $this->_showMessage('网站关闭注册');
        $ruid = S::gp('ruid','G', 2);
        
        header('Cache-control: private, must-revalidate');
        session_cache_limiter("private");
        
        $registerCheck = getCookieValue('reg');
        if ($registerCheck)
        {
            $this->_showMessage('半个小时内只许注册一次');
        }
        
        $denyRegisterIps = setting('denyregister');
        if (!empty($denyRegisterIps))
        {
            $denyArray = explode("|", $denyRegisterIps);
            if (is_array($denyArray) && in_array(ONLINE_IP, $denyArray))
            {
                exit;
            }
        }
        
        if (isset($_POST['mobile']))
        {
            $mobile = S::gp('mobile','P');
            $username = S::gp('username','P');
            $password = S::gp('password','P');
            
            if (empty($mobile) || $mobile < 1300000000 || $mobile > 19000000000)
            {
                $this->_showMessage('请输入正确的手机号');
            }
            
            try
            {
                Members::validateUserName($username);
            }
            catch (UserNameValidateException $exce)
            {
                $this->_showMessage($exce->getMessage());
            }
            if (123456 == $password)
            {
                $this->_showMessage('为了您帐号的安全，请不要使用123456这种简单密码，您可以试试123334类似这种');
            }
            if (empty($password) || mb_strlen($password,'utf8') > 20 || mb_strlen($password,'utf8') < 6)
            {
                $this->_showMessage('密码长度不能超过20位且不能小于6位');
            }
            if (preg_match('/\s/i',$password))
            {
                $this->_showMessage('密码不能含有空格');
            }
            
            $nameCheck = $this->db()->getValue('SELECT COUNT(*) FROM '.Members::table().' WHERE username = '.S::sqlEscape($username));
            if ($nameCheck > 0)
            {
                $this->_showMessage('您填写的用户名已经被注册，请换一个');
            }
            
            $mobileCheck = $this->db()->getValue('SELECT COUNT(*) FROM '.Members::table().' WHERE mobile = '.S::sqlEscape($mobile));
            if ($mobileCheck > 0)
            {
                $this->_showMessage('您填写的手机号已经被注册，请换一个');
            }
            
            $p = $password;
            $password = md5($password);
            do
            {
                $iorange = $this->_iorange();
                $iorangeCheck = $this->db()->getValue('SELECT COUNT(*) FROM '.Members::table().' WHERE iorange='.S::sqlEscape($iorange));
            } while ($iorangeCheck);
            
            $mData = array(
                'username' => $username,
                'mobile' => $mobile,
                'iorange' => $iorange,
                'password' => $password,
                'regdate' => CTIME,
                'lastvisit' => CTIME,
                'lastactivity' => CTIME,
                'regip' => ONLINE_IP,
                'groupid' => setting('defaultgid'),
                'ads' => setting('adsnum'),
            );
            
            $this->db()->insert(Members::table())->value($mData)->q();
            $uid = $this->db()->getInsertId();
            if (!$uid)
            {
                $this->_showMessage('注册失败，请返回重试');
            }
            $this->db()->insert(Memberfields::table())->value(array('uid'=>$uid,'regchannels'=>getRequestSource()))->q();
            $this->db()->insert(MemberExts::table())->value(array('uid'=>$uid))->q();
            $sql = 'UPDATE '.BbsInfo::table().' SET totalmember = totalmember + 1, newmember = '.S::sqlEscape($username."\t".$uid).' WHERE id=1';
            $this->db()->query($sql);
            
            if ($ruid)
            {
                $user = $this->db()->getValue('SELECT COUNT(*) FROM '.Members::table().' WHERE uid='.$ruid);
                if ($user)
                {
                    $this->db()->insert(Reward::table())->value(array('uid'=>$uid,'ruid'=>$ruid,'reward'=>setting('reward'),'createdate'=>date('Y-m-d H:i:s')))->q();
                }
            }

            $feed = '{{'.$uid.'}}加入了'.setting('webname').'大家庭';
            iFeed::single()->create($feed, $uid, 'member');
            if (setting('regaward'))
            {
                $icredit = iCredits::single($uid, $username);
                $icredit->addMoney(setting('regaward'));
            }

            if (!empty($_SESSION['user']['returnUrl']))
            {
                $returnUrl = urldecode($_SESSION['user']['returnUrl']);
                if (false !== strpos($returnUrl, 'sid='))
                {
                    $returnUrl = preg_replace('/sid=(\w+){0,}/is', 'sid='.$iorange, $returnUrl);
                }
                else
                {
                    if (false === strpos($returnUrl, '?'))
                    {
                        $returnUrl .= '?sid='.$iorange;
                    }
                    else
                    {
                        $tmp = explode('?', $returnUrl);
                        count($tmp) > 1 && !empty($tmp[1]) ? $returnUrl .= '&amp;sid='.$iorange : $returnUrl .= 'sid='.$iorange;
                    }
                }
                $message[] = '返回'.ilink('刚才页面', $returnUrl);
            }
            setCookieValue('reg', 1, CTIME + 1800, '/');
            
            if ($this->getController()->isWebRequest())
            {
                setCookieValue('iOrangeUser', strCode($uid."\t".$password."\t".$mobile));
                if ($this->getController()->isAjaxRequest())
                {
                    die(json_encode(array('status' => 1, 'msg' => '恭喜，注册成功！', 'msgCount' => 0, 'userName' => $username)));
                }
                
                $forwardUrl = url('index');
                if (!empty($returnUrl))
                {
                    $forwardUrl = $returnUrl;
                }
                $forwardUrl = cleanSid($forwardUrl);
                iforward($forwardUrl);
            }
            $GLOBALS['iorange_id'] = $uid;
            $GLOBALS['sid'] = $iorange;
            $path = setting('basehost') . setting('path');
            $message[] = "您已成功注册,以下两种方法选择一种,即可实现-自动登录书签:<br/>1、点我要登陆后到达首页,把首页存为书签.<br/>2、请把".$path."index.php?sid=".$iorange."添加到手机'书签'中.任意一种方法都可.<br/><a href='".$path . "index.php?sid=".$iorange."'>返回首页</a>";
            
            $this->showMessage($message);
        }
        
        $this->getController()->render('register',array('ruid'=>$ruid));
    }
}