<?php

	/**
		+---------------------------------------------------------------
		| 开单大师（专业的房产ERP管理系统）
		+---------------------------------------------------------------
		| © 2018 http://www.kaidandashi.com All rights reserved.
		+---------------------------------------------------------------
		| 本系统由淮南市银泰软件科技有限公司提供技术支持
		+---------------------------------------------------------------
		| QQ号：2159094518
		+---------------------------------------------------------------
	*/
   
/*-----------------------------------权限函数开始-------------------------------------*/

function bumen_option($selected,$node_id){
    $x = $node_id ? _rbac_lists_where($node_id,0) : "null";
    $tree = new \Org\Util\Tree();
    $parentid = $selected;
    $result = M('bumen')->order(array("sort" => "ASC"))->select();
    foreach ($result as $key => $r) {
        $r['selected'] = $r['id'] == $parentid ? 'selected' : '';
        if ($x && $x != "all" && $x != "me" && $x != "null") {
            $b = explode(",",$x);
            if (in_array($r['id'],$b)) {
                $array[] = $r;
            }
        }elseif($x == 'me' || $x == false){
            $array = "";
        }elseif($x == 'all' || $x == 'null'){
            $array[] = $r;
        }
    }
    $a = 0;
    $l = 999;
    if ($x && $x != "all" && $x != "me" && $x != "null") {
        foreach ($array as $key => $value) {
            if ($value['level'] < $l) {
                $a = $value['parentid'];
                $l = $value['level'];
            }
        }
    }
    $str = "<option  value='\$id' title='\$bmming' \$selected>\$spacer \$bmming</option>";
    $tree->init($array);
    $select_categorys = $tree->get_tree($a, $str);
    return $select_categorys;
}

function bumen($id){
    $find = M('bumen')->where(array('id'=>$id))->find();
    $txt = $find['bmming'];
    $u = $find['level'];
    for ($i=0; $i < $u; $i++) { 
        $find = M('bumen')->where(array('id'=>$find['parentid']))->find();
        if ($find['bmming']) {
             $txt = $find['bmming']."—".$txt;
        }
    }
    return $txt;
}

/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc'){
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

/*设置权限页面是否选中*/
function _is_have_node($node_id,$role_id,$fanwei,$zhuangtai,$type){
    $where['node_id'] = $node_id;
    $where['role_id'] = $role_id;
    $where['zhuangtai'] = $zhuangtai;
    $where['fanwei'] = $fanwei;
    $is_true = M('access')->where($where)->find();
    if ($is_true) {
        if ($type==1) {
            return "checked";
        }else{
            return "selected";
        }
    }else{
        return "";
    }
}

function _rbac_bumen_show($node_id,$zhuangtai){
    $fanwei = _rbac_range($node_id,$zhuangtai);
    if (!$fanwei) {
        return false;
    }elseif ($fanwei=='all') {
        return 'all';
    }elseif ($fanwei=='me') {
        return 'me';
    }
    
    $arr =_rbac_bumen_top_id($fanwei);
    if (!$arr) {
        return false;
    }
    return $arr["id"];
}

function _rbac_bumen_top_id($val){
    $b_id = M('yonghu')->where(array('id'=>session('uid')))->getField('bumen');
    $find = M('bumen')->where(array('id'=>$b_id))->find();
    $i = $find['level'];
    if ($find['level']<$val) {
        return false;
    }elseif ($find['level']==$val) {
        return $find;
    }elseif ($find['level']>$val) {
        $u = $find['level']-$val;
        for ($i=0; $i < $u; $i++) { 
            $find = M('bumen')->where(array('id'=>$find['parentid']))->find();
        }
        return $find;
    }
}

function _rbac_bumen_array($array,$id=0){
    $arr = array();
    foreach ($array as $v) {
        if ($v['parentid']==$id) {
            $arr[] = $v['id'];
            $a = _rbac_bumen_array($array,$v['id']);
            $arr = array_merge($arr, $a); 
        }
    }
    return $arr;
}

//获取相应节点和状态的 范围值
function _rbac_range($node_id,$zhuangtai){
    if(session('username') == C('RBAC_SUPERADMIN')){
        return 'all';
    }
    
    $role_id=M('role_user')->where(array('user_id'=>session('uid')))->getField('role_id');
    $where['node_id'] = $node_id;
    $where['role_id'] = $role_id;
    $where['zhuangtai'] = $zhuangtai;
    $fanwei = M('access')->where($where)->find();
    if (!$fanwei) {
        return false;
    }
    if (!$fanwei['fanwei']){
        return 'all';
    }
    $me_level = _rbac_me_level();
    if ($fanwei['fanwei']==$me_level) {
        return 'me';
    }
    return $fanwei['fanwei'];
}


//获取范围生成逗号分隔的字符串
function _rbac_in_bumen_string($node_id,$zhuangtai){
    $fanwei = _rbac_range($node_id,$zhuangtai);
    if (!$fanwei) {
        return false;
    }elseif ($fanwei=='all') {
        return 'all';
    }elseif ($fanwei=='me') {
        return 'me';
    }
    
    $arr =_rbac_bumen_top_id($fanwei);
    if (!$arr) {
        return false;
    }
    
    $bumen_array = M('bumen')->select();
    $arr_string = _rbac_bumen_array($bumen_array,$arr['id']);
    $arr_string[] = $arr['id'];
    $string = implode(',',$arr_string);
    return $string;
}

//根据节点状态和对应的人物 查看是否有权限
function _rbac_btn_show($node_id,$zhuangtai,$uid){
    $string = _rbac_in_bumen_string($node_id,$zhuangtai);
    if (!$string) {
        return false;
    }elseif ($string=='all') {
        return true;
    }elseif ($string=='me') {
        if ($uid==session('uid')) {
            return true;
        } else {
            return false;
        }
    }
    
    $map['bumen'] = array('in',$string);
    $map['id'] = $uid;
    $find = M('yonghu')->where($map)->find();
    if ($find) {
        return true;
    }else{
        return false;
    }
}

function _rbac_node_show($node_id){
    if(session('username') == C('RBAC_SUPERADMIN')){
        return true;
    }
    $role_id=M('role_user')->where(array('user_id'=>session('uid')))->getField('role_id');
    $where['node_id'] = $node_id;
    $where['role_id'] = $role_id;
    $find = M('access')->where($where)->find();
    if ($find) {
        return true;
    }else{
        return false;
    }
}

function _rbac_me_level(){
    $bumen_option_value = M('options')->where(array('option_name'=>'bumen_options'))->getField('option_value');
    $bumen_option_value_arr = json_decode($bumen_option_value,true);
    $count = count($bumen_option_value_arr['bumen_array']);
    return $count+1;
}

function _rbac_lists_where($node_id,$zhuangtai){
    $string = _rbac_in_bumen_string($node_id,$zhuangtai);
    if (!$string) {
        return false;
    }elseif ($string=='all') {
        return 'all';
    }elseif ($string=='me') {
        return 'me';
    }
    
    return $string;
}

/*-----------------------------------权限函数结束-------------------------------------*/

// 分析枚举类型配置值 格式 a:名称1,b:名称2
function parse_config_attr($string) {
    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if(strpos($string,':')){
        $value  =   array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k]   = $v;
        }
    }else{
        $value  =   $array;
    }
    return $value;
}

/**
 * 获取数据库中的配置列表
 * @return array 配置数组
 */

function lists(){
    $map    = array('status' => 1);
    $data   = M('Configure')->where($map)->field('type,name,value')->select();
    
    $config = array();
    if($data && is_array($data)){
        foreach ($data as $value) {
            $config[$value['name']] =parse($value['type'], $value['value']);
        }
    }
    return $config;
}

/**
 * 根据配置类型解析配置
 * @param  integer $type  配置类型
 * @param  string  $value 配置值
 */
function parse($type, $value){
    switch ($type) {
        case 3: //解析数组
            $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
            if(strpos($value,':')){
                $value  = array();
                foreach ($array as $val) {
                    list($k, $v) = explode(':', $val);
                    $value[$k]   = $v;
                }
            }else{
                $value =    $array;
            }
            break;
    }
    return $value;
}

function findCityByIp($ip){
    $data = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
    $dizhi = json_decode($data,$assoc=true);
    $country = $dizhi['data']['country'];
    if (($country == "台湾") || ($country == "澳门") || ($country == "香港")) {
        $country = "中国";
    }
    return $country." ".$dizhi['data']['region']." ".$dizhi['data']['city']." ".$dizhi['data']['isp'];
}

function zym($zyid,$zylx){
    if ($zylx == 1) {
        $zym=M('xingzhengqu')->where(array('id'=>$zyid))->getField('xzqming');
    } elseif ($zylx == 2) {
        $zym=M('pianqu')->where(array('id'=>$zyid))->getField('pianqum');
    } elseif ($zylx == 3) {
        $zym=M('xiaoqu')->where(array('id'=>$zyid))->getField('xiaoqum');
    } elseif ($zylx == 4) {
        $zym=M('xuequ')->where(array('id'=>$zyid))->getField('xuexiaom');
    } elseif ($zylx == 5) {
        $zym=M('yonghu')->where(array('id'=>$zyid))->getField('ygmingcheng');
    } elseif ($zylx == 6) {
        $find = M('bumen')->where(array('id'=>$zyid))->find();
        $zym = $find['bmming'];
        $u = $find['level'];
        for ($i=0; $i < $u; $i++) { 
            $find = M('bumen')->where(array('id'=>$find['parentid']))->find();
            if ($find['bmming']) {
                $zym = $find['bmming']."—".$zym;
            }
        }
    } elseif ($zylx == 7) {
        $zym=M('bumen')->where(array('id'=>$zyid))->getField('bmming');
    } elseif ($zylx == 8) {
        $zym=M('role')->where(array('id'=>$zyid))->getField('remark');
    } elseif ($zylx == 10) {
        $zym=M('zdxinxi')->where(array('id'=>$zyid))->getField('zdming');
    } elseif ($zylx == 11) {
        $zym=M('dyxinxi')->where(array('id'=>$zyid))->getField('dyming');
    } elseif ($zylx == 12) {
        $zym=M('lcxinxi')->where(array('id'=>$zyid))->getField('lcming');
    } elseif ($zylx == 13) {
        $zym=M('fjxinxi')->where(array('id'=>$zyid))->getField('fanghao');
    } elseif ($zylx == 14) {
        $zym=M('yonghu')->where(array('id'=>$zyid))->getField('dianhua');
    } elseif ($zylx == 15) {
        $zym=M('yonghu')->where(array('id'=>$zyid))->getField('ygbianhao');
    }
    return $zym;
}

function yhbm($id,$lx){
    $bm=M('yonghu')->where(array('id'=>$id))->getField('bumen');
    if ($lx == 1) {
        $yhbm=$bm;
    } elseif ($lx == 2) {
        $yhbm=zym($bm,7);
    } elseif ($lx == 3) {
        $yhbm=zym($bm,6);
    }
    return $yhbm;
}

function get_s_img($id){
    $img_urlf=M('photo')->where(array('fybh'=>$id,'fengmian'=>1))->getField('image');
    $img_url=M('photo')->where(array('fybh'=>$id))->order('create_time desc')->limit(1)->getField('image');
    if ($img_urlf) {
        return $img_urlf;
    }else{
        return $img_url;
    }
}

function get_x_img($id){
    $img_urlf=M('xqphoto')->where(array('xqid'=>$id,'fengmian'=>1))->getField('image');
    $img_url=M('xqphoto')->where(array('xqid'=>$id))->order('create_time desc')->limit(1)->getField('image');
    if ($img_urlf) {
        return $img_urlf;
    }else{
        return $img_url;
    }
}

function get_peizhi($zdun,$zhi){
    if($zhi){
        $lxming=M('peizhi')->where(array('pzming'=>$zdun,'lxid'=>$zhi))->getField('lxming');
        return $lxming;
    }else{
        $arr=M('peizhi')->where(array('pzming'=>$zdun,'zhuangtai'=>1))->select();
        return $arr;
    }
}

function get_user($id,$lx){
    if (!$id) {
        return "";
    }
    $user=M('yonghu')->where('id='.$id)->find();
    if (!$user) {
        return "";
    }
    $bm=M('bumen')->where('id='.$user['bumen'])->getField('bmming');
    if ($lx=="1") {
        return $user['ygmingcheng'];
    }elseif ($lx=="2") {
        return $user['dianhua'];
    }elseif ($lx=="3") {
        return $bm;
    }
}

function p ($arr){
	echo '<pre>' . print_r($arr,true) . '</pre>';
}

function J($str){
	return str_replace('./', '', str_replace('//', '/', $str));
}

/**
 * 获取客户端浏览器类型
 * @return string 浏览器类型返回字符串 unknown为未知浏览器类型
*/

function getBrowser(){
    $agent=$_SERVER["HTTP_USER_AGENT"];
    if(strpos($agent,'MSIE')!==false || strpos($agent,'rv:11.0')) //ie11判断
    return "ie";
    else if(strpos($agent,'Firefox')!==false)
    return "firefox";
    else if(strpos($agent,'Chrome')!==false)
    return "chrome";
    else if(strpos($agent,'Opera')!==false)
    return 'opera';
    else if((strpos($agent,'Chrome')==false)&&strpos($agent,'Safari')!==false)
    return 'safari';
    else
    return 'unknown';
}

/**
 * 上传文件类型控制 此方法仅限ajax上传使用
 * @param  string   $path    字符串 保存文件路径示例： /Upload/image/
 * @param  string   $format  文件格式限制
 * @param  integer  $maxSize 允许的上传文件最大值 52428800
 * @return booler   返回ajax的json格式数据
 */

function ajax_upload($path='file',$format='image',$maxSize='52428800'){
    ini_set('max_execution_time', '0');
    // 去除两边的/
    $path=trim($path,'/');
    // 添加Upload根目录
    $path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
    // 上传文件类型控制
    $ext_arr= array(
        'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
        'photo' => array('jpg', 'jpeg', 'png'),
        'flash' => array('swf', 'flv'),
        'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
        'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
    );
    if(!empty($_FILES)){
        // 上传文件配置
        $config=array(
            'maxSize'   =>  $maxSize,               // 上传文件最大为50M
            'rootPath'  =>  './',                   // 文件上传保存的根路径
            'savePath'  =>  './'.$path.'/',         // 文件上传的保存路径（相对于根路径）
            'saveName'  =>  array('uniqid',''),     // 上传文件的保存规则，支持数组和字符串方式定义
            'autoSub'   =>  false,                  // 自动使用子目录保存上传文件 默认为true
            'exts'      =>  ''//isset($ext_arr[$format])?$ext_arr[$format]:'',
        );
        // 实例化上传
        $upload=new \Think\Upload($config);
        // 调用上传方法
        $info=$upload->upload();
        $data=array();
        $Img = D('Photo');  
        if(!$info){
            // 返回错误信息
            $error=$upload->getError();
            $data['error_info']=$error;
            echo json_encode($data);
        }else{
            // 返回成功信息
            foreach($info as $file){
                //上传的图片同步保存到数据库表
                $d['gongsiid'] = session('gongsiid');  
                $d['uid'] = session('uid');
                $d['image'] = $file['savename'];
                $d['fybh'] = $_POST['fybh'];
                $d['create_time'] = time();
                $Img->add($d);
                //把fangyuan表tupian字段更新为 1
                M('Fangyuan')->where(array('bianhao'=>$_POST['fybh']))->setField('tupian',1);
                M('fangyuan')->where(array('bianhao'=>$_POST['fybh']))->setField('xiugaisj',time());
                $data_rizhi['zy_type']=1;
                $data_rizhi['uid']=session("uid");
                $data_rizhi['addtime']=time();
                $data_rizhi['cz_type']=12;
                $fyid=M('fangyuan')->where(array('bianhao'=>$_POST['fybh']))->getField('id');
                $data_rizhi['zy_id']=$fyid;
                $data_rizhi['zy_bianhao']=$_POST['fybh'];
                $neirong="上传图片";
                $data_rizhi['neirong']=$neirong;
                M('rizhi')->add($data_rizhi);
                //为上传成功的图片生成缩略图
                $timg = new \Think\Image();
                $timg->open(trim($file['savepath'].$file['savename']));
                $newpathbig =  trim($file['savepath']).'b_'.substr($file['savename'],0,strrpos($file['savename'], '.')).'.'.$file['ext'];
                $newpath =  trim($file['savepath']).'t_'.substr($file['savename'],0,strrpos($file['savename'], '.')).'.'.$file['ext'];
                $timg->thumb(900,600)->save($newpathbig);
                $timg->thumb(450,300)->save($newpath);
                if (C('IS_PHOTO_JSY')==1) {
                    // 给原图添加水印
                    $timg->open($newpathbig)->water('./Upload/shuiyin/shuiyin1.png',\Think\Image::IMAGE_WATER_CENTER,C('IS_PHOTO_TOUMING'))->save($newpathbig);
                    $timg->open($newpath)->water('./Upload/shuiyin/shuiyin1.png',\Think\Image::IMAGE_WATER_CENTER,C('IS_PHOTO_TOUMING'))->save($newpath);
                }
                //删除原图
                unlink('./Upload/'.session('gongsiid').'/'.$_POST['fybh'].'/'.$file['savename']);
                rename($newpathbig,'./Upload/'.session('gongsiid').'/'.$_POST['fybh'].'/'.$file['savename']);
                //返回给AJAX
                $data['name']=trim($file['savepath'].$file['savename'],'.');
                echo json_encode($data);
            }
        }
    }
}

function ajax_upload_xq($path='file',$format='image',$maxSize='52428800'){
    ini_set('max_execution_time', '0');
    // 去除两边的/
    $path=trim($path,'/');
    // 添加Upload根目录
    $path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
    // 上传文件类型控制
    $ext_arr= array(
        'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
        'photo' => array('jpg', 'jpeg', 'png'),
        'flash' => array('swf', 'flv'),
        'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
        'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
    );
    if(!empty($_FILES)){
        // 上传文件配置
        $config=array(
            'maxSize'   =>  $maxSize,               // 上传文件最大为50M
            'rootPath'  =>  './',                   // 文件上传保存的根路径
            'savePath'  =>  './'.$path.'/',         // 文件上传的保存路径（相对于根路径）
            'saveName'  =>  array('uniqid',''),     // 上传文件的保存规则，支持数组和字符串方式定义
            'autoSub'   =>  false,                  // 自动使用子目录保存上传文件 默认为true
            'exts'      =>  ''//isset($ext_arr[$format])?$ext_arr[$format]:'',
        );
        // 实例化上传
        $upload=new \Think\Upload($config);
        // 调用上传方法
        $info=$upload->upload();
        $data=array();
        $Img = D('xqphoto');
        if(!$info){
            // 返回错误信息
            $error=$upload->getError();
            $data['error_info']=$error;
            echo json_encode($data);
        }else{
            // 返回成功信息
            foreach($info as $file){
                //上传的图片同步保存到数据库表
                $d['gongsiid'] = session('gongsiid');  
                $d['uid'] = session('uid');
                $d['image'] = $file['savename'];
                $d['xqid'] = $_POST['xqid'];
                $d['create_time'] = time();
                $Img->add($d);
                //把fangyuan表tupian字段更新为 1
                M('Xiaoqu')->where(array('id'=>$_POST['xqid']))->setField('tupian',1);
                //为上传成功的图片生成缩略图
                $timg = new \Think\Image();
                $timg->open(trim($file['savepath'].$file['savename']));
                $newpathbig =  trim($file['savepath']).'b_'.substr($file['savename'],0,strrpos($file['savename'], '.')).'.'.$file['ext'];
                $newpath =  trim($file['savepath']).'t_'.substr($file['savename'],0,strrpos($file['savename'], '.')).'.'.$file['ext'];
                $timg->thumb(900,600)->save($newpathbig); 
                $timg->thumb(450,300)->save($newpath);
                if (C('IS_PHOTO_JSY')==1) {
                    // 给原图添加水印
                    $timg->open($newpathbig)->water('./Upload/shuiyin/shuiyin1.png',\Think\Image::IMAGE_WATER_CENTER,C('IS_PHOTO_TOUMING'))->save($newpathbig);
                    $timg->open($newpath)->water('./Upload/shuiyin/shuiyin1.png',\Think\Image::IMAGE_WATER_CENTER,C('IS_PHOTO_TOUMING'))->save($newpath);
                }
                //删除原图
                unlink('./Upload/'.session('gongsiid').'/xiaoqu/'.$_POST['xqid'].'/'.$file['savename']);
                rename($newpathbig,'./Upload/'.session('gongsiid').'/xiaoqu/'.$_POST['xqid'].'/'.$file['savename']);
                //返回给AJAX
                $data['name']=trim($file['savepath'].$file['savename'],'.');
                echo json_encode($data);
            }               
        }
    }
}

function get_xiugai($xiugaiqian,$xiugaihou,$pzming){
    $xgqian=M('peizhi')->where(array('pzming'=>$pzming,'lxid'=>$xiugaiqian))->getField('lxming');
    $xghou=M('peizhi')->where(array('pzming'=>$pzming,'lxid'=>$xiugaihou))->getField('lxming');
    $zhushi=M('peizhi')->where(array('pzming'=>$pzming))->getField('zhushi');
    return $zhushi."：[".$xgqian."]=>[".$xghou."]；";
}

function get_xgbm($xiugaiqian,$xiugaihou,$bmming){
    $xgqian=M('bumen')->where(array('id'=>$xiugaiqian))->getField('bmming');
    $xghou=M('bumen')->where(array('id'=>$xiugaihou))->getField('bmming');
    return "部门：[".$xgqian."]=>[".$xghou."]；";
}

function get_xgjs($xiugaiqian,$xiugaihou,$remark){
    $xgqian=M('role')->where(array('id'=>$xiugaiqian))->getField('remark');
    $xghou=M('role')->where(array('id'=>$xiugaihou))->getField('remark');
    return "岗位：[".$xgqian."]=>[".$xghou."]；";
}