<?php


class OUser
{
	const SECRET_KEY = '@4!@#$%@';
	
	static public function GenPassword($p) {
		return md5($p . self::SECRET_KEY);
	}

	static public function Create($user_row) {

		$user_row['password'] = self::GenPassword($user_row['password']);
		$user_row['create_time'] = $user_row['login_time'] = time();
		$user_row['ip'] = Utility::GetRemoteIp();
		
		$user_row['id'] = DB::Insert('user', $user_row);
		if ( $user_row['id'] == 1 ) {
			Table::UpdateCache('user', $user_row['id'], array(
						'manager'=>'Y',
						
						));
		}
		return $user_row['id'];
	}

	static public function GetUser($user_id) {
		if (!$user_id) return array();
		return DB::GetTableRow('user', array('id' => $user_id));
	}

    static public function GetUserId($user_name){
        $user = Table::Fetch('user',$user_name,'username');
        return $user['id'];
    }
	static public function GetLoginCookie($cname='ru') {
		$cv = cookieget($cname);
		if ($cv) {
			$zone = base64_decode($cv);
			$p = explode('@', $zone, 2);
			return DB::GetTableRow('user', array(
				'id' => $p[0],
				'password' => $p[1],
			));
		}
		return Array();
	}

	static public function Modify($user_id, $newuser=array()) {
		if (!$user_id) return;
		
		$table = new Table('user', $newuser);
		$table->SetPk('id', $user_id);
		if ($table->password) {
			$plainpass = $table->password;
			$table->password = self::GenPassword($table->password);
		}
		return $table->Update( array_keys($newuser) );
	}
    
    
	static public function GetLogin($email, $unpass, $en=true) {
		if($en) $password = self::GenPassword($unpass);
		$field = strpos($email, '@') ? 'email' : 'username';
		$zuituuser = DB::GetTableRow('user', array(
					$field => $email,
					'password' => $password,
		));
		if ($zuituuser)  return $zuituuser;
		return array();
	}
}

function ut1(){
    global $INI;
    global $login_user_id;
    $login_user_id = 1;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");
    $user_row = array();
    $user_row['username'] = "gegewuu";
    $user_row['email'] = "gegewuu@gmail.com";
    $user_row['password'] = "aa09090909";
    $user_row['mobile'] = "15030165612";
    echo OUser::Create($user_row);
}

function ut2(){
    global $INI;
    global $login_user_id;
    $login_user_id = 1;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");

    $user = OUser::GetLogin('easenet@gmail.com', 'aa09090909');
    print_r($user);
    echo "<br />";
    $user = OUser::GetUser(2);
    print_r($user);
}


function ut3(){
    global $INI;
    global $login_user_id;
    $login_user_id = 1;
    include_once(dirname(dirname(dirname(__FILE__))) . "/app.php");

    $user_row['zipcode'] = '050021';
    $user_row['address'] = '东风路218号';
    $user_row['realname'] = '武华';
    OUser::Modify(2,$user_row);
}
?>
