<?php
/**
* 用户注册
* @author moufer<moufer@163.com>
* @package modoer
* @copyright Moufer Studio(www.modoer.com)
* @version $Id: reg.php 6 2008-01-03 10:46 $
*/
define('SCRIPTNAV', 'reg');
require_once(substr(dirname(__FILE__), 0, -6).'./include/common.inc.php');

$forward = !$forward && $php_referer ? $php_referer : ($forward ? $forward : $_config['siteurl']);
if(strposex($forward,'logout=1') || !strposex($forward,$php_domain)) {
    $forward = $_config['siteurl'];
}
$forward = html_special_chars($forward);

// Passport 整合
$_passport['enable'] && location($_passport['reg_url'], false);

if($user->isLogin && !$logout) {
    $urls = array(
        array('name'=>'我的助手','url'=>$_config['siteurl'].'member/index.php'),
        array('name'=>'返回首页','url'=>$_config['siteurl']),
        array('name'=>'注销登录','url'=>$_config['siteurl'].'member/login.php?logout=1'),
    );
    redirect('您目前处于登录状态，无法注册新帐户，请退出后再进行注册。', $urls);
}

if(check_submit('regsubmit')) {

    if($_config['closereg']){
        redirect('网站暂时关闭了会员注册功能。');
    }

    if($_seccode['registry'] && ($_DCOOKIE['seccode'] != formhash(strtolower($seccode),'',''))) {
        redirect('验证码错误，请返回。');
    }

    if($ucenter_enable) {
        if(!empty($activation)) {
            $result = $user->Activation($activation);
            !$result && redirect($user->errmsg, $user->backurl);
            redirect('恭喜您，激活成功！'.$result, $_config['siteurl'].'member/index.php'); // $result -- UC 同步登入的HTML，不可删除
        } else {
            $result = $user->Register($username, $password, $email);
            !$result && redirect($user->errmsg, $user->backurl);
            $result = $user->Login($username, $password);
            !$result && redirect($user->errmsg);
            redirect('恭喜您，注册成功！'.$result, $_config['siteurl'].'member/index.php'); // $result -- UC 同步登入的HTML，不可删除
        }
    }

    require_once(MUDDER_ROOT.'./member/include/fun_reg.php');
    $username = addslashes(trim(stripslashes($username)));
    $password = trim($password);
    $email = trim($email);
    switch( validateusername($username) ) {
    case -1:
        $error .= '未填写用户名!'.'<br />';
        break;
    case 1:
        $error .= '用户名不能大于15个字符!'.'<br />';
        break;
    case 2:
        $error .= '用户名不得包含(,)、(*)、(")、([TAB])、([SPACE])、([\r])、([\n])、(&lt;)、(&gt;)、(&amp;)其中之一'.'<br />';
        $username = preg_replace("/(c:\\con\\con$|[%,\*\"\s\t\<\>\&])/i","",$username);
        break;
    case 3:
        $error .= '用户名中存在敏感和非法字符!'.'<br />';
        break;
    }
    switch( validateEmail($email) ) {
    case -1:
        $error .= '请输入邮箱地址!'.'<br />';
        break;
    case 1:
        $error .= '邮箱地址字符不能大于40个字符!'.'<br />';
        break;
    case 2:
        $error .= '您输入的邮箱地址不正确!'.'<br />';
        break;
    }
    if($password != addslashes($password)) {
        $error .= '请输入密码!'.'<br />';
    } else {
        switch( validatePassword($password) ) {
        case -1:
            $error .= '请输入密码!'.'<br />';
            break;
        case 1:
            $error .= '密码的长度必须控制在6-20个字符以内!'.'<br />';
            break;
        case 2:
            $error .= '密码中只能包含数字，字母以及"_ ~ ! @ #"!'.'<br />';
            break;
        }
    }
    if($password != $password_s) {
        $error .= '2次输入的密码不一致!'.'<br />';
        break;
    }
    if(!$error) {
        if(!$_config['existsemailreg']) {
            $c = $db->get_one("SELECT COUNT(*) AS count FROM {$dbpre}members WHERE email='$email'");
            if($c['count'] >= 1) {
                $error .= 'E-mail地址已存在!<br />';
            }
        }
        if(!$error) {
            $c = $db->get_one("SELECT COUNT(*) AS count FROM {$dbpre}members WHERE username='$username'");
            if($c['count'] >=1 ) {
                $error .= '用户名已存在!'.'<br />';
            } else {
                $md5pw = md5($password);
                if(!$db->query("INSERT INTO {$dbpre}members (email,username,password,regdate,logintime,loginip,logincount,groupid) VALUES ('$email','$username','$md5pw','$timestamp','$timestamp','$onlineip','1','10')")) {
                    $error .= '注册失败!'.'<br />';
                } else {
                    $uid = $db->insert_id();

                    // 注册会员增加积分;
                    $uppoint = intval(addslashes($_expleve['reg']['point']));
                    $upcoin = intval(addslashes($_expleve['reg']['coin']));
                    if($uppoint != 0 && $upcoin != 0) {
                        $db->update("UPDATE {$dbpre}members SET point=point+$uppoint,coin=coin+$upcoin WHERE uid='$uid'"); 
                    }

                    $rp = array("\$sitename", "\$username", "\$time");
                    $sm = array($_config['sitename'], $username, date("Y-m-d H:i:s", $timestamp));

                    $spacename = $_space['spacename'];
                    $spacedescribe = $_space['spacedescribe'];
                    if(empty($_space['spacename'])) {
                        $spacename = '$username的个人空间';
                    }
                    if(empty($_space['spacedescribe'])) {
                        $spacedescribe = "读万卷书，行万里路。";
                    }
                    $spacename = str_replace($rp, $sm, $spacename);
                    $spacedescribe = str_replace($rp, $sm, $spacedescribe);
                    $db->query("INSERT INTO {$dbpre}spaces(uid,space_styleid,spacename,spacedescribe,pageview) VALUES('$uid','{$_config['space_styleid']}','$spacename','$spacedescribe','0')");

                    if($_config['salutatory']) {
                        $subject = '欢迎注册'.$_config['sitename'].'会员';
                        if(!$_config['salutatory_msg']) {
                            $content = "敬爱的会员：$username\r\n欢迎您注册成为".$_config['sitename']."会员。\r\n\r\n".$_config['sitename']."\r\n".date("Y-m-d H:i:s",$timestamp);
                        } else {
                            $content = str_replace($rp, $sm, $_config['salutatory_msg']);
                        }

                        require_once(MUDDER_ROOT."./member/model/message.php");
                        MessageModel::send(0, $uid, $subject, $content);

                    }
                    //更新统计缓存
                    $_webtotal['totalmember'] ++;
                    update_webtotal();
                    // 登录操作
                    $life = 3600*24*30; //Cookie保存1个月
                    $hash = formhash($uid, $username, $md5pw);
                    set_Cookie("uid", $uid, $life);
                    set_Cookie("username", $username, $life);
                    set_Cookie("hash", $hash, $life);
                    set_Cookie("logintime", $timestamp, $life);
                    set_Cookie("remembertime", $timestamp + $life, $life);
                    if($_config['passport_discuz_enable']){
                        // 整合passport API
                        require_once(MUDDER_ROOT.'include/passport.func.php');
                        $member = array (
                            'cookietime' => $remember_time,
                            'time' => $timestamp,
                            'username' => $username,
                            'password' => $md5pw,
                            'email' => $email,
                            'regdate' => $timestamp,
                            'regip' => $onlineip,
                        );
                        $auth = passport_encrypt(passport_encode($member), $_config['passport_discuz_passportkey']);
                        $action = 'login';
                        $verify = md5($action . $auth . $forward . $_config['passport_discuz_passportkey']);
                        $url = $_config['siteurl'] . $_config['passport_discuz_passportpath'] .
                            '?action='.$action.
                            '&auth='.rawurlencode($auth).
                            '&forward='.rawurlencode($forward).
                            '&verify='.$verify;
                        location($url,false);
                    } else {
                        redirect('恭喜您，注册成功！',$_config['siteurl'].'member/index.php');
                    }
                }
            }
        }
    }
} else {
	if($action == 'activation') {
		list($activeuser) = explode("\t", uc_authcode($auth, 'DECODE'));
	}
    if($_config['showregrule']) {
        $regrule = $db->get_value("SELECT value FROM {$dbpre}config WHERE variable='regrule'");
    }
		
}

$subtitle = '用户注册';
require_once MUDDER_ROOT.'header.php';
require_once template('member_reg');
footer();
?>