<?php
/**
 * [LJCMS] (C)2012-2099 LJdev,Inc.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2014.04.03
 */

class control extends oabase
{
    public function action_login()
    {
        //    $is_verify_code = $this->get_system_config("login_verify_code");
        TPL::display($this->cptpl . 'login.tpl');
    }

    // 登录检测
    public function action_check_login()
    {
        $is_verify_code = $this->get_system_config();
        if (!empty($is_verify_code['login_verify_code'])) {
            parent::loadUtil('session');
            if ($_POST['verify'] != XSession::get('verifycode')) {
                XHandle::halt('对不起，验证码不正确！', '', 1);
            }
        }

        if (empty($_POST['emp_no'])) {
            XHandle::halt('对不起，帐号必须！', '', 1);
            $this->error('！');
        } elseif (empty($_POST['password'])) {
            XHandle::halt('密码必须！', '', 1);
        }

        if ($_POST['emp_no'] == 'admin') {
            $_SESSION['ADMIN_AUTH_KEY'] = true;
        }

        // if(C("LDAP_LOGIN")&&!$is_admin){
        if (false) {
            $where['emp_no'] = array('eq', $_POST['emp_no']);
            $dept_name       = D('UserView')->where($where)->getField('dept_name');

            if (empty($dept_name)) {
                XHandle::halt('帐号或密码错误！', '', 1);
            }

            $ldap_host = C("LDAP_SERVER");//LDAP 服务器地址
            $ldap_port = C("LDAP_PORT");//LDAP 服务器端口号
            $ldap_user = "CN=" . $_POST['emp_no'] . ",OU={$dept_name}," . C('LDAP_BASE_DN');
            $ldap_pwd  = $_POST['password']; //设定服务器密码
            $ldap_conn = ldap_connect($ldap_host, $ldap_port) or die("Can't connect to LDAP server");

            ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
            $r = ldap_bind($ldap_conn, $ldap_user, $ldap_pwd);//与服务器绑定
            if ($r) {
                $map['emp_no'] = $_POST['emp_no'];
                $map["is_del"] = array('eq', 0);
                $model         = M("User");
                $auth_info     = $model->where($map)->find();
            } else {
                $this->error(ldap_error($ldap_conn));
            }
        } else {

            $model = parent::model('login', 'oa');
            $map   = array();
            // 支持使用绑定帐号登录
            $map['emp_no']   = $_POST['emp_no'];
            $map["is_del"]   = 0;
            $map['password'] = md5($_POST['password']);
            //print_r($map);die;
            $auth_info = $model->check_login($map);
        }

        //使用用户名、密码和状态的方式进行认证
        if (false == $auth_info) {
            XHandle::halt('帐号或密码错误！', '', 1);
        } else {
            $_SESSION['USER_AUTH_KEY'] = $auth_info['id'];
            $_SESSION['emp_no']        = $auth_info['emp_no'];
            $_SESSION['user_name']     = $auth_info['name'];
            $_SESSION['user_pic']      = $auth_info['user_pic'];
            $_SESSION['dept_id']       = $auth_info['dept_id'];
            //保存登录信息
            $ip                      = $this->get_client_ip();
            $time                    = time();
            $data                    = array();
            $data['last_login_time'] = $time;
            $data['login_count']     = $auth_info['login_count'] + 1;
            $data['last_login_ip']   = $ip;
            $model->save($auth_info['id'], $data);
            header('Location: oa.php');
        }
    }

    public function action_logout()
    {
        if (!empty(parent::$wrap_admin['username'])) {
            $this->saveLoginLog(parent::$wrap_admin['username'], '退出登录', 1);
        }
        $model = parent::model('login', 'am');
        $model->logout();
        unset($model);
        XHandle::redirect($this->cpfile . '?c=Public&a=login');
    }


    /**
     * 获取客户端IP地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    public function get_client_ip($type = 0, $adv = false)
    {
        $type = $type ? 1 : 0;
        static $ip = NULL;
        if ($ip !== NULL) return $ip[$type];
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) unset($arr[$pos]);
                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}