<?php
    /** 
        +-------------------------------------------------------------------------
        | 房佳（专业的新房分销ERP管理系统）
        +-------------------------------------------------------------------------
        | Copyright (c) 2008-2019 http://fj.ytsofts.cn/ All rights reserved.
        +-------------------------------------------------------------------------
        | 本系统由淮南市银泰软件科技有限公司提供技术支持
        +-------------------------------------------------------------------------
        | QQ号：984784483
        +-------------------------------------------------------------------------
    */
   
/*-----------------------------------权限函数开始-------------------------------------*/

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($config,$role_id,$fanwei,$zhuangtai,$type){
    foreach ($config as $key => $value) {
        if ($value['zhuangtai'] == $zhuangtai && $value['fanwei'] == $fanwei) {
            if ($type == 1) {
                return "checked";
            }else{
                return "selected";
            }
        }
    }
    return "";
}

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;
}

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

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 node_merge($node, $access = null,$pid=0){
	$arr = array();
	foreach ($node as $v) {
		if (is_array($access)) {
			$v['access'] = in_array($v['id'],$access) ? 1 : 0;
		}
		if ($v['pid']==$pid) {
			$v['child'] = node_merge($node,$access,$v['id']);
			$arr[]=$v;
		}
	}
	return $arr;
	
}

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

/**
 * 获取客户端浏览器类型
 * @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';
}

function format_date($time){
    $t=time()-$time;
    $f=array(
        '31536000'=>'年',
        '2592000'=>'个月',
        '604800'=>'星期',
        '86400'=>'天',
        '3600'=>'小时',
        '60'=>'分钟',
        '1'=>'秒'
    );
    foreach ($f as $k=>$v)    {
        if (0 !=$c=floor($t/(int)$k)) {
            return $c.$v.'前';
        }
    }
}

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

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);
                //把xiaoqu表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(800,800)->save($newpathbig); 
                $timg->thumb(300,300)->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."]；";
}