where($voiceCond)->limit($limit)->order('id desc')->select(); if(!$audioList){ json_fail('没有语音了'); } $audioList = array_reverse($audioList); foreach($audioList as &$v){ $v['created_at'] = date('Y-m-d H:i:s', $v['created_at']); } json_success('获取成功',$audioList); } public function getChatDevices( ){ header('Access-Control-Allow-Origin: *'); //json_fail('登录失败'); $userid= I('get.userid'); $hasDevices = M('devices')->where(['user_id' => $userid])->getField('imei, device_name'); if(!$hasDevices){ json_fail('名下查询不到设备'); } $imeis = array_keys($hasDevices); $cond = [ 'card_no' => ['in', $imeis], 'type' => 1 ]; $chatList = M('kq_voice')->field('card_no as imei, MAX(`created_at`) as lastTime, sum(case when hasread = 0 then 1 else 0 end) AS unreadCount')->where($cond)->group('card_no')->select(); if(!$chatList){ $chatList = []; foreach($hasDevices as $k => $v){ $avatar = M('devices')->where(['imei' => $k])->getField('avatar'); $arr = [ 'imei' => $k, 'lastTime' => '暂无互动哦!', 'unreadCount' => 0, 'device_name' => $v, 'avatar' => $avatar ? $avatar : '' ]; array_push($chatList, $arr); } }else{ foreach($chatList as &$v){ $avatar = M('devices')->where(['imei' => $v['imei']])->getField('avatar'); $v['awayTime'] = $this->getHumenTime( time() - (int)$v['lastTime'] ); $v['dateTime'] = date('Y-m-d H:i:s', $v['lastTime']); $v['device_name'] = $hasDevices[$v['imei']]; $v['avatar'] = $avatar ? $avatar : ''; } } json_success('消息获取成功', $chatList); } private function getHumenTime( $timeInterval ){ if ($timeInterval < 60){ $formatime = $timeInterval.'秒'; }elseif($timeInterval < 60 * 60){ $min = floor($timeInterval/60); $formatime = $min.'分钟'; }elseif($timeInterval < 60 * 60 * 24){ $h = floor($timeInterval/(60*60)); $formatime = $h.'小时'; }elseif($timeInterval < 60 * 60 * 24 * 30){ $d = floor($timeInterval/(60*60*24)); $formatime = $d.'天'; }elseif($timeInterval < 60 * 60 * 24 * 30 * 12){ $m = floor($timeInterval/(60*60*24*30)); $formatime = $m.'月'; }else{ $y = floor($timeInterval/(60*60*24*30*12)); $formatime = $y.'年'; } return $formatime; } public function saveParentUploadAudio( ){ header('Access-Control-Allow-Origin: *'); $imei = $_POST['imei']; $file = $_FILES['upfile']; $userid = $_POST['userid']; if(!$imei){ json_fail('获取不到设备标识,请返回上一页重进'); } if(!$userid){ json_fail('获取不到Y用户标识'); } $ext = pathinfo($file['name'], PATHINFO_EXTENSION); if($ext != 'wav'){ json_fail('不是音频文件'); } //文件保存目录 $folder = realpath(__ROOT__).'/static/assets/wav/'.date('Ymd').'/'; if (!is_dir($folder)){ mkdir($folder,0777,true); } $uploadfile = $folder . basename($file['name']); if (move_uploaded_file($file['tmp_name'], $uploadfile)) { //1.获取语音时长 $time = $this->getVoiceTime($uploadfile); //2.语音大小 $size = $file['size']; //3.语音url $url = 'http://'.$_SERVER['HTTP_HOST'].'/static/assets/wav/'.date('Ymd').'/'.basename($file['name']); //4.设备code $data = array( 'card_no'=>$imei, 'file'=>$url, 'size'=>$size, 'time'=>$time, 'user_id' => $userid, 'type' => 2, 'result'=> 0, 'created_at'=>time() ); //保存数据 $id=M('kq_voice')->createAdd($data); if($id){ sendVoiceIdToCtwing($imei,$id); json_success('保存成功'); }else{ json_fail('保存失败'); } } else { json_fail('发送文件失败'); } json_success('success'); } private function getVoiceTime( $file, $base ){ $fp = fopen($file, 'r'); if (fread($fp, 4) != 'RIFF') { return ''; } fseek($fp, 20); $rawheader = fread($fp, 16); $header = unpack('vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits', $rawheader); $pos = ftell($fp); while (fread($fp, 4) != 'data' && !feof($fp)) { $pos++; fseek($fp, $pos); } $rawheader = fread($fp, 4); $data = unpack('Vdatasize', $rawheader); $sec = $data[datasize] / $header[bytespersec]; if ($base == 60) { $seconds = intval($sec % 60); $minutes = intval(($sec - $sec * 60) / 60); return $minutes . ':' . $seconds; } else { return round($sec); } } public function updateAudioStatus( ){ header('Access-Control-Allow-Origin: *'); $id = I('get.vid'); if(!$id){ json_fail('获取不到语音消息标识'); } $res = M('kq_voice')->where(['id' => $id])->save(['hasread' => 1]); if($res === false){ json_fail('已读状态修改失败'); } json_success('已读状态修改成功'); } public function login_test( ){ header('Access-Control-Allow-Origin: *'); //json_fail('登录失败'); $openid = I('get.openid'); /* if(!$openid){ json_fail('用户未授权'); } */ $data = json_decode( file_get_contents("php://input") ,true); $cond = array( 'username'=>$data['mobile'], ); $user_info = M('users')->where($cond)->find(); if(!$user_info){ json_fail('用户不存在'); } //if($user_info['password'] != password_hash($data['password'],PASSWORD_DEFAULT) ){ // json_fail('密码不正确1'); //} if(!password_verify($data['password'], $user_info['password'])){ json_fail('密码不正确'); } if($user_info['wx_open_id'] != $openid){ $update = array( 'wx_open_id'=>$openid ); $result = M('users')->createSave($cond,$update); if(!$result){ json_fail('登陆失败'); } } //如果当前openid与其他账号openid相同,清空其他表中openid $where = array( 'wx_open_id' => $openid, 'id' => ['NEQ', $user_info['id']], ); $result = M('users')->createSave($where,['wx_open_id'=>'']); if(!$result){ json_fail('登陆失败'); } /* $oid_info = M('users')->where($where)->find(); if($oid_info['id'] != $user_info['id']){ $result = M('users')->createSave($where,['wx_open_id'=>'']); if(!$result){ json_fail('登陆失败'); } }*/ json_success('登录成功', $user_info['id']); } public function register( ){ header('Access-Control-Allow-Origin: *'); // 通过手机号和短信验证码注册 $data = json_decode( file_get_contents("php://input") ,true); // 用户类型:个人(personal)、团体(group) $userType = $data['userType']; // 设备类型:卡牌(card)、徽章(badge) $deviceType = $data['deviceType']; // 团体卡牌用户(group_card_user) 不可注册 // 个人用户(personal),团体徽章用户(group_badge_user) 可注册 if ($userType == 'personal') { // 个人用户 $identify = 'personal'; } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户 $identify = 'group_badge_user'; } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户 // $identify = 'group_card_user'; json_fail('团体卡牌用户无需注册,请联系发卡人询问账号!'); } else { json_fail('未知用户类型'); } if(!$data['phone']){ json_fail('手机号码不能为空'); } if(!$data['smsCode']){ json_fail('短信验证码不能为空'); } if(! $data['password']){ json_fail('密码不能为空'); } if(! $data['confirmPassword']){ json_fail('请输入确认密码'); } if ($data['password'] != $data['confirmPassword']) { json_fail('两次密码不一致'); } /* $cond = array( 'username'=>$data['phone'] ); $user_info = M('users')->where($cond)->join('user_has_roles ON users.id = user_has_roles.uid')->find(); if($user_info){ //存在用户则判断 $role_identify=M('roles')->where(array('id'=>$user_info['role_id']))->getField('identify'); if($role_identify==$identify){ json_fail('该类型用户已经存在,请前往登陆'); } }*/ // 获取角色id $roleId = M('roles')->where(['identify' => $identify])->getField('id'); if (!$roleId) { json_fail('未知角色类型'); } // 判断角色、号码是否已注册 $userinfo = M('users')->alias('a')->where(['username'=>$data['phone']])->join("INNER JOIN user_has_roles b ON a.id = b.uid AND b.role_id = {$roleId}")->find(); if ($userinfo) { json_fail('该号码已注册'); } // 验证码有效性 $res = $this->isValidSmsCode($data['phone'], $data['smsCode']); if (!$res['success']) { json_fail($res['message']); } //if($user_info['password'] != password_hash($data['password'],PASSWORD_DEFAULT) ){ $savePwd = password_hash($data['password'],PASSWORD_DEFAULT); $saveData = [ 'username' => $data['phone'], 'realname' => '用户'.$data['phone'], 'password' => $savePwd, 'phone' => $data['phone'], 'created_at' => time(), ]; // 个人用户给定默认部门 if ($identify == 'personal') { $where = [ 'type' => 'basic_config', 'field' => 'department_id', ]; $department_id = M('sys_config')->where($where)->getField('fieldValue'); if ($department_id) { $saveData['department_id'] = $department_id; } } M()->startTrans(); $userid = M('users')->add($saveData); if(!$userid){ M()->rollback(); json_fail('注册失败'); } $hasRoleData = [ 'uid' => $userid, 'role_id' => $roleId ]; $userHasRoleRes = M('user_has_roles')->add($hasRoleData); if(!$userHasRoleRes){ M()->rollback(); json_fail('注册失败'); } M()->commit(); json_success('注册成功',$userid); } public function login( ){ header('Access-Control-Allow-Origin: *'); //json_fail('登录失败'); $openid = I('get.openid'); if(!$openid){ json_fail('未授权,请关闭当前页面重新进入'); } $data = json_decode( file_get_contents("php://input") ,true); // 用户类型:个人(personal)、团体(group) $userType = $data['userType']; // 设备类型:卡牌(card)、徽章(badge) $deviceType = $data['deviceType']; if ($userType == 'personal') { // 个人用户 $identify = 'personal'; } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户 $identify = 'group_badge_user'; } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户 $identify = 'group_card_user'; } else { json_fail('未知用户类型'); } $role_id = M('roles')->where(array('identify'=>$identify))->getField('id'); if (!$role_id) { json_fail('未知用户类型2'); } $cond = array( 'username' => $data['username'], ); $user_info = M('users')->alias('u')->where($cond)->join("INNER JOIN user_has_roles AS r ON u.id = r.uid AND r.role_id = {$role_id}")->find(); if(!$user_info){ $identifyArrs=['personal','group_badge_user','group_card_user']; $other_user=[]; foreach($identifyArrs as $item){ if($item == $identify){ continue; } $other_role = M('roles')->where(array('identify'=>$item))->find(); if (!$other_role) { continue; } $other_user_info = M('users')->alias('u')->where($cond)->join("INNER JOIN user_has_roles AS r ON u.id = r.uid AND r.role_id = {$other_role['id']}")->count(); if($other_user_info){ $other_user[]=$other_role['role_name']; }else{ continue; } } $other_count=count($other_user); if($other_count==2){ json_fail('账号类型错误'); }elseif($other_count==1){ json_fail('账号类型错误,请选择'.$other_user[0]); }else{ json_fail('账号不存在'); } json_fail('账号错误'); } if(!password_verify($data['password'], $user_info['password'])){ json_fail('密码错误'); } $where = array( 'wx_open_id' => $openid, 'id' => ['NEQ', $user_info['uid']], ); //$result = M('users')->createSave($where,['wx_open_id'=>'']); $result = M('users')->where($where)->save(['wx_open_id'=>'']); if($result===false){ json_fail('登陆失败'); } if($user_info['wx_open_id'] != $openid){ $update = array( 'wx_open_id' => $openid, 'last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_time' => time(), ); $result = M('users')->createSave(array('id'=>$user_info['uid']),$update); if(!$result){ json_fail('登陆失败'); } } //如果当前openid与其他账号openid相同,清空其他表中openid //查询用户未同步设备 $imei_list=M('devices')->where(array('user_id'=>$user_info['uid']))->getField('imei',true); if($imei_list){ foreach($imei_list as $val){ $result=$this->addToVoiceCenter($val); if(!$result['success']){ create_log($val.'同步失败 message: '.$result['message'], 'AddVoiceCenter'); json_fail('登陆失败,网络异常'); } } } $res = array( 'id'=>$user_info['uid'], 'realname'=>$user_info['realname'], 'avatar' => $user_info['avatar'], 'phone'=>$user_info['phone'], ); json_success('登录成功', $res); } public function getLastPositionMulti( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid){ json_fail('未检测到用户标识'); } $devices = M('devices')->where(['user_id' => $userid])->select(); if(!$devices){ json_fail('名下查询不到任何设备'); } $resp = []; foreach($devices as &$locationInfo){ //new start $isThirdParty = M('third_party_devices')->where(['device_imei' => $locationInfo['imei']])->count(); if($isThirdParty){ $thindLoc = $this->getThirdLocation($locationInfo['imei']); if($thindLoc){ $locationInfo['lng'] = $thindLoc['lon']; $locationInfo['lat'] = $thindLoc['lat']; $locationInfo['time'] = $thindLoc['receiveAt']; } } //new end //wifi_online_time //wifi_longitude //wifi_latitude //addr $locationInfo['isAlarm'] = $locationInfo['alarm_status']; $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ; $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time']; $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude']; $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude']; if(!$isThirdParty){ $locationInfo['address'] = $locationInfo['address']; } // if(!$locationInfo['time']){ $locationInfo['awayTime'] = '从未在线'; }else{ $timeInterval = time() - (int)$locationInfo['time']; $locationInfo['awayTime'] = $this->getHumenTime($timeInterval); } $lngLatAlter = new \Jms\Algo\Geometry(); if(!$locationInfo['lat'] || !$locationInfo['lng']){ continue; } if($isThirdParty){ $latLng = $lngLatAlter->wgsTOgcj($locationInfo['lat'], $locationInfo['lng']); $locationInfo['lat'] = $latLng['lat']; $locationInfo['lng'] = $latLng['lng']; }else{ $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']); $locationInfo['lat'] = $latLng['lat']; $locationInfo['lng'] = $latLng['lng']; } $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']); array_push($resp, $locationInfo); } if(!$resp){ json_fail('暂无任何设备上报过数据哦!'); } json_success('查询成功', $resp); } private function checkLoginState( $openid, $userid ){ $wx_open_id=M('users')->where(array('id'=>$userid))->getField('wx_open_id'); if($wx_open_id === 'test_openid'){ return array('status'=>true,'message'=>''); } if($wx_open_id!=$openid){ //已被他人登录 return array('status'=>false,'message'=>'账号可能在其他设备登录,请重新登录'); } return array('status'=>true,'message'=>''); } public function getMyDevices( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $list=M('devices')->where(array('user_id'=>$userid))->select(); $type_id=M('sys_dict_type')->where(['code'=>'DeviceType'])->getField('id'); $rela_type_id=M('sys_dict_type')->where(['code'=>'Relationships'])->getField('id'); foreach($list as &$val){ $val['badge_user_info']=M("badgeuser")->where(['id'=>$val['badge_user_id']])->find(); $val['device_type']=M('sys_dict_data')->where(['type_id'=>$type_id,'code'=>$val['device_type']])->getField('value'); $val['department_name']=M('departments')->where(['id'=>$val['department_id']])->getField('department_name'); if(!$val['device_name'] || $val['device_name']==null){ $val['device_name']='设备'.substr($val['imei'],-4); } $cond = ['device_id'=>$val['id']]; $res = M('kq_urgent')->where($cond)->select(); if($res){ foreach($res as &$item){ $item['relationship']=M('sys_dict_data')->where(['type_id'=>$rela_type_id,'code'=>$item['relationship']])->getField('value'); } $val['urgent_list']=$res; } } if(!$list){ json_fail('暂无绑定设备'); } json_success('查询成功',$list); } public function getNews( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $where = ['id' => $userid]; $userinfo = M('users')->where($where)->field('department_id')->find(); if (empty($userinfo)) { json_fail('未获取到用户信息'); } $level_str = M('departments')->where(array('id'=>$userinfo['department_id']))->getField('level'); if($level_str){ $levelArr = explode('-', $level_str); }else{ $levelArr =[]; } array_push($levelArr,$userinfo['department_id']); $page = I('get.page') ? I('get.page') : 1; $pageSize = 10; $newsModel = M('news'); $start = ($page - 1) * $pageSize; $cond = [ 'status' => 1, 'department_id' => array('in',$levelArr) ]; $list = $newsModel->where($cond)->limit( $start, $pageSize)->order('created_at desc')->select(); //$list = $newsModel->limit( $start, 10)->select(); $total = $newsModel->where($cond)->count() ?: 0; foreach($list as &$v){ $v['updated_at_datetime'] = date('Y-m-d H:i:s',$v['updated_at']); $v['creator'] = M('users')->where(['id' => $v['creator_id'] ])->getField('username') ? : 'admin'; } if (!$list) { $list = []; } $resp = [ 'list' => $list, 'total' => $total, 'pageSize' => $pageSize ]; json_success('获取成功', $resp); } public function getUrgentList( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } $openid = I('get.openid'); $device_id = I('get.device_id'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } if($device_id){ $cond=array('id'=>$device_id); }else{ $cond=array('user_id'=>$userid); } $device_list=M('devices')->where($cond)->field('id,imei,rfid,device_name,device_type')->select(); if(!$device_list){ json_fail('暂无绑定设备'); } $type_id=M('sys_dict_type')->where(['code'=>'Relationships'])->getField('id'); foreach($device_list as &$val){ if ($val['device_name'] === '' || $val['device_name'] === null) { $name = substr($val['imei'], -4); $val['device_name'] = '设备'. $name; } $cond = ['device_id'=>$val['id']]; $res = M('kq_urgent')->where($cond)->select(); if($res){ foreach($res as &$item){ $item['relationship']=M('sys_dict_data')->where(['type_id'=>$type_id,'code'=>$item['relationship']])->getField('value'); } $val['urgent_list']=$res; } } json_success('获取成功', $device_list); } public function getAlarmList( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } $openid = I('get.openid'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $imeiArr=M('devices')->where(['user_id' => $userid])->getField('imei',true); $page = I('get.page') ? I('get.page') : 1; $pageSize = 10; $start = ($page - 1) * $pageSize; $cond = []; $alarmType = I('get.alarmType'); $imei = I('get.imei'); if(!$imei){ $cond['device_number'] = array('in',$imeiArr); }else{ $cond['device_number'] = $imei; } if($alarmType){ $cond['alarm_type'] = $alarmType; } $list = M('alarm_report')->where($cond)->limit( $start, $pageSize)->order('created_at desc')->select(); $type_id=M('sys_dict_type')->where(array('code'=>'AlarmType'))->getField('id'); foreach($list as &$val){ $val['alarm_type_str']=M('sys_dict_data')->where(array('type_id'=>$type_id,'code'=>$val['alarm_type']))->getField('value'); $val['created_at_str'] = date('Y-m-d H:i:s', $val['created_at']); } $total = M('alarm_report')->where($cond)->count() ?: 0; $resp = [ 'list' => $list ?:[], 'total' => $total, 'pageSize' => $pageSize ]; json_success('获取成功', $resp); } public function getSignaturEtc( ){ header('Access-Control-Allow-Origin: *'); $url = I('get.url'); if(!$url){ json_fail('no url'); } $url = urldecode($url); $accessToken = $this->getWeixinAccessToken(); if (!$accessToken) { json_fail('获取 access token 失败'); } $apiTiket = $this->getJsapiTikcet($accessToken); if(is_array($apiTiket)){ json_fail($apiTiket['errcode'].':'.$apiTiket['errmsg']); } $noncestr = substr(md5(time()), 0, 16); $timestamp = time(); //jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value $str = 'jsapi_ticket='.$apiTiket.'&noncestr='.$noncestr.'×tamp='.$timestamp.'&url='.$url; $signature = sha1($str); $data = [ 'appId' => C('WECHAT_APPID'), 'timeStamp' => $timestamp, 'nonceStr' => $noncestr, 'signature' => $signature, 'url' => $url, 'jsapi_ticket' =>S('wx_jsapi_ticket'), 'accessToken' => $accessToken, ]; json_success('get success', $data); } private function getJsapiTikcet( $accessToken ){ $jsapiTicket = S('wx_jsapi_ticket'); if(!$jsapiTicket){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$accessToken .'&type=jsapi'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = json_decode(curl_exec($ch), true); curl_close($ch); if($output['errcode'] != 0){ return $output; } S('wx_jsapi_ticket', $output['ticket'], '7100'); return $output['ticket']; }else{ return $jsapiTicket; } } public function getActivity( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } $openid = I('get.openid'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } // 查出学生所在部门 $where = ['id' => $userid]; $userinfo = M('users')->where($where)->field('department_id')->find(); if (empty($userinfo)) { json_fail('未获取到用户信息'); } $page = I('get.page') ? I('get.page') : 1; $pageSize = 10; $actModel = M('activity'); $start = ($page - 1) * $pageSize; $cond = [ 'status' => 1, 'department_id' => $userinfo['department_id'] ]; $list = $actModel->where($cond)->limit( $start, $pageSize)->select(); $total = $actModel->where($cond)->count() ?: 0; foreach($list as &$v){ $v['updated_at_datetime'] = date('Y-m-d H:i:s',$v['updated_at']); $v['start_time'] = date('Y-m-d H:i:s',$v['start_time']); $v['end_time'] = date('Y-m-d H:i:s',$v['end_time']); $v['creator'] = M('users')->where(['id' => $v['creator_id'] ])->getField('username') ? : 'admin'; $applyCount = M('activity_has_users')->where(['activity_id' => $v['id']])->count(); $v['apply_count'] = $applyCount ? $applyCount : 0; } if (!$list) { $list = []; } $resp = [ 'list' => $list, 'total' => $total, 'pageSize' => $pageSize ]; json_success('获取成功', $resp); } public function getGpsRoutes( ){ header('Access-Control-Allow-Origin: *'); $imei = I('get.imei'); $startTime = I('get.startTime'); $endTime = I('get.endTime'); if(!$imei){ json_fail('获取不到设备号'); } if(!$startTime){ json_fail('无起始时间'); } if(!$endTime){ json_fail('无结束时间'); } //end_time //start_time //student_id //queyRouteListByStudentId $routeInfo = []; $lngLatAlter = new \Jms\Algo\Geometry(); //new start $isThirdParty = M('third_party_devices')->where(['device_imei' => $imei])->count(); if($isThirdParty){ $imei = M('users')->where(['id' => $studentId])->getField('imei'); $option = [ 'startTime' => strtotime($startTime), 'endTime' => strtotime($endTime), 'pageSize' => 500 ]; $thirdRoutes = $this->getThirdRoutes($imei, $option); $routes = $thirdRoutes['content']; if(!$routes){ json_success('success', $routeInfo); } foreach($routes as $item){ $latLng = $latLng = $lngLatAlter->wgsTOgcj($item['lat'], $item['lon']); $arr =[ 'OnlineTime' => $item['receiveAt'], 'lat' => $latLng['lat'], 'lng' => $latLng['lng'] ]; array_push($routeInfo, $arr); } }else{ $routeInfo = queyGpsRouteListByimei($imei, $startTime, $endTime); //$routeInfo = analyzeRouteInfoGaodeBatch($routeInfo); $routeInfo = analyzeRouteInfoWayzBatch($routeInfo); $arr = []; foreach($routeInfo as &$v){ $v['lat'] = $v['Latitude']; $v['lng'] = $v['Longitude']; if($v['lat']){ array_push($arr, $v); } } $routeInfo =bmapFilterOutliers($arr); } json_success('success', $routeInfo); } private function analyzeRouteInfo( $list ){ if(!$list){ return array(); } $arr= []; foreach($list as $k=> $v){ if(isset($v['WifiMacs']) && $v['WifiMacs'] !=''){ $wifiRes =$this->requestWifiLBS($v); if($wifiRes['success']){ if($wifiRes['data']['lon'] == '' || is_null($wifiRes['data']['lat'])){ continue; } $list[$k]['Latitude'] = $wifiRes['data']['lat']; $list[$k]['Longitude'] = $wifiRes['data']['lon']; $list[$k]['SignalType'] = 'WiFi'; $list[$k]['WifiAddress'] = $wifiRes['data']['address']; array_push($arr, $list[$k]); }else{ // array_splice($list,$k,1); continue; } }else{ $list[$k]['SignalType'] = 'GPS'; array_push($arr, $list[$k]); } } return $arr; } private function requestWifiLBS( $routeInfo ){ if(!$routeInfo){ return array( 'success' => false, 'msg' => '空数据' ); } if(!isset( $routeInfo['WifiMacs']) ){ return array( 'success' => false, 'msg' => '无wifi信息' ); } $WifiMacs = $routeInfo['WifiMacs']; $userKey = ''; if(!$userKey){ $userKey = 'f107b0b3a513e6e37c6fb0424bed6633'; } //$url = 'http://api.cellocation.com:81/loc/?wl=' . $WifiMacs .'&output=json&coord=gcj02'; $url = 'http://apilocate.amap.com/position?accesstype=1&imei=' . $routeInfo['DeviceNumber'] . '&macs=' . $WifiMacs . '&key=' . $userKey; $curl = curl_init($url); curl_setopt($curl, CURLOPT_TIMEOUT, 3); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); if (curl_errno($curl)) { $errmsg = curl_error($curl); curl_close($curl); return array( 'success' => false, 'msg' => $errmsg ); } curl_close($curl); $response = json_decode($response, true); if($response['info'] != 'OK' || count($response['result']) <2 ){ return array( 'success' => false, 'msg' => $response['info'] ); } $result = $response['result']; $location = $response['result']['location']; $location = explode(',', $location); $response = array( 'lon' => $location[0], 'lat' => $location[1], 'address' => $result['desc'] ); return array( 'success' => true, 'data' => $response ); } private function registerDevice2third( $deviceImei ){ $tokenInfo = $this->getThirdTokenInfo(); if(!$tokenInfo){ return false; } $postData = [ "deviceImei" => $deviceImei, "phone" => "", "userId" => $tokenInfo['holder'] ]; var_dump($postData); $url = "http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/device"; $headers[] = "Content-Type: application/json"; $headers[] = "Authorization: ". $tokenInfo['token']; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($postData) ); $output = curl_exec($ch); curl_close($ch); if($output === false){ $this->push_log('thirdapi_register_device_curl_error',curl_error($curl)); return false; } $deviceRes = json_decode($output, ture) ; if($deviceRes['error'] || $deviceRes['code']){ $this->push_log('thirdapi_register_device_response_error',$deviceRes); return false; } $this->push_log('thirdapi_register_device_response_success',$deviceRes); return true; } private function getThirdRoutes( $imei, $option ){ /* { "page": 0, "size": 6000, "total": 8, "content": [{ "collectDt": "2021-07-07 10:33:39", "receiveAt": "2021-07-07 10:33:39", "lat": "40.02577751048506", "lon": "116.35762812669113", "battery": 91, "positionType": 2, "imei": "71041607133", "isOnline": null }] } */ if (!$imei) { $this->push_log('thirdapi_devicelocation_curl_error', 'imei 为空'); return false; } $tokenInfo = $this->getThirdTokenInfo(); if(!$tokenInfo){ return false; } $pageNo = $option['pageNo'] ? $option['pageNo'] : 0; $pageSize = $option['pageSize'] ?$option['pageSize']: 6000; $startTime = isset($option['startTime']) ? $option['startTime'] * 1000 : ''; $endTime = isset($option['endTime']) ? $option['endTime'] * 1000 : ''; $positionTypes = $option['positionTypes'] ? $option['positionTypes']: ''; $headers[] = "Content-Type: application/json"; $headers[] = "Authorization: ". $tokenInfo['token']; $url = 'http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/devicedata/location/filter?imei='.$imei.'&pageNo='.$pageNo.'&pageSize='.$pageSize.'&startTime='.$startTime.'&endTime='.$endTime.'&positionTypes='.$positionTypes; //var_dump($url); $response = $this->http_get($url, $headers); if (!$response) { $this->push_log('thirdapi_devicelocation_curl_error', $response); return false; } return json_decode($response, true); } private function getThirdLocation( $imei ){ if (!$imei) { $this->push_log('third_newlocation_curl_error', 'imei 为空'); return false; } $tokenInfo = $this->getThirdTokenInfo(); if(!$tokenInfo){ return false; } $headers[] = "Content-Type: application/json"; $headers[] = "Authorization: ". $tokenInfo['token']; $url = 'http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/devicedata/location/'.$imei; $response = $this->http_get($url, $headers); if (!$response) { $this->push_log('third_lastLocation_error', $response); return false; } return json_decode($response, true); } private function http_get( $url, $headers ){ $oCurl = curl_init(); if(!$headers){ $headers = []; } if(stripos($url,"https://")!==FALSE){ curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); } curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers ); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 ); $sContent = curl_exec($oCurl); $aStatus = curl_getinfo($oCurl); if(intval($aStatus["http_code"])==200){ curl_close($oCurl); return $sContent; }else{ $this->push_log('thirdapi_token_curl_error',curl_error($oCurl)); curl_close($oCurl); return false; } } public function sendSmsCode( ){ header('Access-Control-Allow-Origin: *'); $postData = json_decode(file_get_contents('php://input'), true) ?:[]; if (!$postData['phone']) { json_fail('手机号码不能为空'); } if (!preg_match('/^1[3456789]\d{9}$/', $postData['phone'])) { json_fail('手机号码格式不正确'); } // 是否重置密码 $isReset = $postData['isReset']; if ($postData['userType'] == 'personal') { // 个人用户 $identify = 'personal'; } elseif ($postData['userType'] == 'group' && $postData['deviceType'] == 'badge') { // 团体徽章用户 $identify = 'group_badge_user'; } elseif ($postData['userType'] == 'group' && $postData['deviceType'] == 'card') { // 团体卡牌用户 $identify = 'group_card_user'; } else { json_fail('暂不支持的用户类型'); } // 注册时检测 if (!$isReset && $identify == 'group_card_user') { json_fail('暂不支持的注册用户类型'); } // 获取角色id $roleId = M('roles')->where(['identify' => $identify])->getField('id'); // 判断角色、号码是否已注册 $userinfo = M('users')->alias('a')->where(['username'=>$postData['phone']])->join("INNER JOIN user_has_roles b ON a.id = b.uid AND b.role_id = {$roleId}")->find(); // 重置密码时 if ($isReset && empty($userinfo)) { json_fail('该号码未注册'); } elseif (!$isReset && $userinfo) { json_fail('该号码已注册'); } $sms_code_mode = M('sms_verification_code'); // 短信验证码模型 // 防盗刷IP地址检测 $todayTime = strtotime(date('Y-m-d')); $where = ['access_ip' => $_SERVER['REMOTE_ADDR'], 'created_at' => ['GT', $todayTime]]; $count = $sms_code_mode->where($where)->count(); if ($count >= 10) { json_fail('已达到当日获取次数上限'); } // 获取短信配置 $rlyunId = M('sms_config')->where(['name' => 'rlyun'])->getField('id'); $smsConfig = M('sms_config')->where(['pid' => $rlyunId])->getField('key,value'); if (empty($smsConfig)) { json_fail('获取短信配置失败'); } // 获取短信验证码模板信息 $where = ['operator' => 'rlyun', 'code' => 'verification_code']; $tmpInfo = M('sms_template')->where($where)->find(); if (empty($tmpInfo)) { json_fail('获取短信验证码模板信息失败'); } // 生成验证码 $code = rand(0, 9999); $code = str_pad($code, 4, '0',STR_PAD_LEFT); // 保存验证码 $time = time(); $saveData = [ 'mobile' => $postData['phone'], 'code' => $code, 'access_ip' => $_SERVER['REMOTE_ADDR'], 'created_at' => $time, 'updated_at' => $time, ]; M()->startTrans(); // 开启事务 $res = $sms_code_mode->createAdd($saveData); if ($res === false) { M()->rollback(); json_fail('发送失败,请稍后重试'); } //M()->commit(); //json_success('测试,不发短信,看数据库'); // 发送短信验证码 $content = str_replace('{1}', $code, $tmpInfo['content']); $content = str_replace('{2}', '5分钟', $content); $contentData = [ 'tplno' => $tmpInfo['identify'], 'tpldata' => [ $code, '5分钟' ], //'tpldata' => $content, // error test 'info' => $content, ]; //$res = (new \Jms\Sms\RlyuntxV100)->send($postData['phone'], $contentData, $smsConfig); $res = send_sms_with_config($postData['phone'], $contentData, $smsConfig); if (!$res['success']) { M()->rollback(); $res = M('sms_send_log')->add($res['data']); json_fail($res['message'] ?: '发送失败'); } M()->commit(); json_success($res['message']); } public function applyCourse( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $post_data = json_decode(file_get_contents('php://input'), true) ?:[]; if (!$post_data['course_id']) { json_fail('未获取到报名课程'); } $courses_model = M('courses'); $apply_user_model = M('apply_users'); // 检测课程是否发布 $where = ['id' => $post_data['course_id'],'publish'=> 1]; $publish = $courses_model->where($where)->getField('publish'); if (!$publish) { json_fail('课程不存在或未发布'); } // 获取用户信息 $where = ['id' => $userid]; $user_info = M('users')->where($where)->find(); if (empty($user_info)) { json_fail('未获取到报名用户信息'); } // 检测是否已报名 $where = ['user_id' => $userid, 'course_id' => $post_data['course_id']]; if ($apply_user_model->where($where)->count()) { json_fail('已报名,请勿重复操作'); } $time = time(); $save_data = [ 'course_id' => $post_data['course_id'], 'user_id'=> $userid, 'apply_time'=> $time, 'department_id' => $user_info['department_id'], 'creator_id' => $userid, 'created_at' => $time, ]; $res = $apply_user_model->createAdd($save_data); if (!$res) { json_fail('报名失败,请稍后重试'); } json_success('报名成功'); } public function getCourseDetail( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $course_id = I('get.id'); if (!$course_id) { json_fail('未获取到课程信息'); } // 查出课程信息 $where = ['id' => $course_id]; $course_info = M('courses')->where($where)->find() ? : []; if ($course_info) { // 查出课程视频 $where = ['course_id' => $course_id,'publish' => 1]; $video_list = M('videos')->where($where)->field('id,name,path,cover_image,introduction,duration,lector_id')->select() ? : []; $users_model = M('users'); foreach ($video_list as &$video) { $video['lector'] = ''; if ($video['lector_id']) { $where = ['id' => $video['lector_id']]; $video['lector'] = $users_model->where($where)->getField('realname') ? : ''; } unset($video['lector_id']); } $course_info['video_list'] = $video_list; // 是否报名 $course_info['apply_status'] = 0; $where = ['course_id' => $course_id, 'user_id' => $userid]; if (M('apply_users')->where($where)->find()) { $course_info['apply_status'] = 1; } } json_success('获取成功', $course_info); } public function getCourseVideos( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } $id = I('get.id'); if (!$id || $id == 'undefined' || $id == 'null') { json_fail('未获取到课程信息'); } // 查出学生所在学校 $where = ['course_id' => $id,'publish' => 1]; $video_list = M('videos')->where($where)->field('name,path,cover_image,introduction,duration')->select() ? : []; json_success('获取成功', $video_list); } public function getUserCourses( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } /* $applyState = I('get.applyState'); $deviceId = I('get.deviceId'); if (!$deviceId) { json_fail('请选择一个设备用户'); }*/ // 查出用户信息 $where = ['id' => $userid]; $user_info = M('users')->where($where)->find(); if (empty($user_info)) { json_fail('获取用户信息失败'); } $total = 0; $limit = I('get.limit') ? : 10; $page = I('get.page') ? : 1; $courses_model = M('courses'); $apply_students_model = M('apply_users'); // 查出该设备所在部门下的课程 $where = [ 'publish' => 1, '_string' => "FIND_IN_SET({$user_info['department_id']}, departments)", ]; // 课程数量 $total = $courses_model->where($where)->count(); // 课程 $course_list = $courses_model->where($where)->order('created_at desc')->page($page,$limit)->select() ?: []; foreach ($course_list as &$course) { // 转换创建时间 $course['created_at'] = date('Y-m-d H:i:s', $course['created_at']); // 报名人数 $where = ['course_id' => $course['id']]; $course['apply_count'] = $apply_students_model->where($where)->count() ? : 0; } $data = [ 'page' => $page, 'limit' => $limit, 'total' => $total, 'list' => $course_list, ]; json_success('获取成功', $data); } public function getVideoDetail( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $id = I('get.id'); if (!$id) { json_fail('未获取到视频信息'); } $where = ['id' => $id,'publish' => 1]; $video_info = M('videos')->where($where)->field('id,name,path,cover_image,introduction,duration,lector_id')->find() ? : []; $video_info['lector'] = ''; if ($video_info['lector_id']) { $where = ['id' => $video_info['lector_id']]; $video_info['lector'] = M('users')->where($where)->getField('realname') ? : ''; } unset($video_info['lector_id']); json_success('获取成功', $video_info); } public function saveVideoPlayingData( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $post_data = file_get_contents("php://input"); $post_data = json_decode($post_data, true) ?: []; if (!isset($post_data['video_id'])) { json_fail('未获取到视频id'); } $post_data['first_play_time'] = $post_data['first_play_time'] ? substr($post_data['first_play_time'], 0 , 10) : time(); // 查出用户所在部门 $where = ['id' => $userid]; $department_id = M('users')->where($where)->getField('department_id'); $post_data['department_id'] = $department_id; // 添加数据 $res = M('video_play')->createAdd($post_data); if (!$res) { json_fail('保存失败'); } json_success('保存成功'); } public function getAlarmTypeOptions( ){ header('Access-Control-Allow-Origin: *'); $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id'); $options = M('sys_dict_data')->field('id, value as text, code as value')->where(['type_id' => $typeid])->select(); if(!$options){ json_fail('获取告警选项失败'); } json_success('获取选项成功', $options); //AlarmType } private function isValidSmsCode( $mobile, $code ){ if (!$mobile) { return ['success' => false, 'message' => '手机号码不存在']; } if (!$code) { return ['success' => false, 'message' => '验证码不存在']; } // 根据手机号码和验证码查询最后一次验证码 $sms_verification_code_model = M('sms_verification_code'); $cond = [ 'mobile' => $mobile, 'code' => $code ]; $info = $sms_verification_code_model->where($cond)->order('created_at', 'desc')->find(); // 不存在 if (empty($info)) { return ['success' => false, 'message' => '验证失败,请确保手机号码和验证码输入无误']; } // 超过时间(暂定5分钟) $valid_time = 60 * 5; if (time() - $info['created_at'] > $valid_time) { return ['success' => false, 'message' => '验证码已失效']; } // 超过使用次数(暂定3次) if ($info['use_times'] >= 3) { return ['success' => false, 'message' => '验证码已失效']; } // 可以使用,使用次数+1 $cond = ['id' => $info['id']]; $res = $sms_verification_code_model->where($cond)->setInc('use_times'); if ($res === false) { return ['success' => false, 'message' => '操作失败,请重试']; } return ['success' => true, 'message' => '验证码有效']; } public function userBindDevice( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } // 通过手机号和短信验证码注册 $data = json_decode( file_get_contents("php://input") ,true); // 用户类型:个人(personal)、团体(group) $userType = $data['userType']; // 设备类型:卡牌(card)、徽章(badge) $deviceType = $data['deviceType']; // 团体卡牌用户(group_card_user) 不可注册 // 个人用户(personal),团体徽章用户(group_badge_user) 可注册 if ($userType == 'personal') { // 个人用户 $identify = 'personal'; } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户 $identify = 'group_badge_user'; } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户 $identify = 'group_card_user'; } else { json_fail('未知用户类型'); } if ($identify == 'group_card_user') { json_fail('无绑定设备权限'); } //$data['imei'],$data['user_no'],$data['username'] if(!$data['imei'] ){ json_fail('缺少IMEI参数'); } //先查询设备信息 看是否被绑定 $where = array('imei'=>$data['imei']); $device_info=M('devices')->where($where)->find(); if(!$device_info){ json_fail('设备不存在,请确认输入无误'); } if($device_info['user_id']){ json_fail('设备已被绑定'); } if ($identify == 'group_badge_user' && $device_info['device_type'] != 1 ) { json_fail('无法绑定该类型的设备'); } $userType = $data['userType']; $device_name = ''; if ($data['device_name']) { $device_name = $data['device_name']; } elseif ($data['username']) { $device_name = $data['username']; } else { $device_name = '用户'. substr($data['imei'], -4); } $save_data=array( 'device_name' => $device_name, 'user_id'=>$userid, 'use_state'=>1, ); M()->startTrans(); if ($identify == 'group_badge_user'){ //团体用户 绑定设备 并绑定用户信息 if( !$data['user_no'] || !$data['username'] ){ json_fail('用户姓名和编号不能为空'); } // 第一次绑定:将 badgeuser 中的 department_id 赋给 users 的 department_id,之后将只能绑定该部门下的设备 // badge_cond $badge_cond = ['user_no'=>$data['user_no'], 'username'=>$data['username']]; $userinfo = M('users')->where(['id'=>$userid])->find(); if ($userinfo['department_id']) { $badge_cond['department_id'] = $userinfo['department_id']; } $badge_info = M('badgeuser')->where($badge_cond)->find(); if(!$badge_info){ json_fail('绑定用户不存在'); } if ($badge_info['is_used']) { json_fail('该用户已绑定'); } // 检测设备与用户是否在同一部门 if ($device_info['department_id'] != $badge_info['department_id']) { json_fail('用户与设备所属部门不一致'); } $update_data=array('is_used'=>1); //$badgeRes=M('badgeuser')->createSave(array('id'=>$badge_info['uid']),$update_data); // 修改徽章用户状态 $badgeRes = M('badgeuser')->where(array('id'=>$badge_info['id']))->setField($update_data); if(!$badgeRes){ M()->rollback(); json_fail('绑定用户失败'); } $save_data['badge_user_id']=$badge_info['id']; // 设置登录用户部门 if (!$userinfo['department_id']) { $res = M('users')->where(['id'=>$userid])->setField(['department_id'=>$badge_info['department_id']]); if($res === false){ M()->rollback(); json_fail('设置用户部门失败'); } } } $devRes=M('devices')->createSave(array('id'=>$device_info['id']),$save_data); if(!$devRes){ M()->rollback(); json_fail('绑定设备失败'); } //未同步设备需要先同步 if($device_info['sync_status']!=1){ $result=$this->addToVoiceCenter($device_info['imei']); if(!$result['success']){ create_log($device_info['imei'].'绑定时同步失败 message: '.$result['messaget'], 'AddVoiceCenter'); M()->rollback(); json_fail('绑定设备失败'); } } M()->commit(); json_success('绑定成功',$userid); } public function getUserFences( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $userid =intval(I('get.userid')); if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } $field = 'id, name, fence_shape as shape, creator_id as userid, is_check_in as inFenceAlarm, is_check_out as outFenceAlarm, fence_info as fenceInfo, sent_interval'; $res = M('fences')->field($field)->where(['creator_id' => $userid, 'fence_type' => 1])->select(); if(!$res){ json_fail('查询不到用户围栏'); } foreach($res as &$v){ $v['inFenceAlarm'] = (bool)($v['inFenceAlarm']); $v['outFenceAlarm'] = (bool)($v['outFenceAlarm']); $v['fenceInfo'] = json_decode($v['fenceInfo'], true); $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($v['fenceInfo']['center']['lat'], $v['fenceInfo']['center']['lng']); $v['fenceInfo']['center']['lat'] = $convPoint['lat']; $v['fenceInfo']['center']['lng'] = $convPoint['lng']; } json_success('查询成功', $res); } public function changeUserFenceAlarmStatus( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $post_data = file_get_contents('php://input'); $post_data = json_decode($post_data, true); $fenceId = $post_data['id']; if(!$fenceId){ json_fail('获取不到围栏标识,请刷新下'); } $alarmType = $post_data['alarmType']; $value = $post_data['value']; if(is_null($value) ){ json_fail('获取不到告警标识值'); } $saveData = []; if($alarmType == 'in'){ $saveData['is_check_in'] = $value; }else{ $saveData['is_check_out'] = $value; } $res = M('fences')->where(['id' => $fenceId])->save($saveData); if(!res){ json_fail('修改告警状态失败'); } json_success('修改告警状态成功'); } public function updateDeviceInfo( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $data = json_decode( file_get_contents("php://input") ,true); $device_id=$data['device_id']; if(!$device_id){ json_fail('缺少设备ID'); } $device_name=$data['device_name']; if(!$device_name){ json_fail('缺少修改信息'); } $cond=array('id'=>$device_id); $res=M('devices')->createSave($cond,array('device_name'=>$device_name)); if(!$res){ json_fail('修改失败'); } json_success('修改成功',$list); } public function getSystemFences( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $userid =intval(I('get.userid')); if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } $userBelongDep = M('users')->where(['id' => $userid ])->getField('department_id'); if(!$userBelongDep){ json_fail('查询不到用户归属组织'); } $departIds = M('departments')->where(['id' => $userBelongDep ])->getField('level'); if($departIds){ $departIds = explode('-', $departIds); }else{ $departIds =[]; } array_push($departIds, $userBelongDep); $typeid = M('sys_dict_type')->where(['code' =>'FenceType'])->getField('id'); $fenceTypeAssoc = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value'); $fenceCond = [ 'fence_type' => ['in', [0, 2]], 'departments' => ['in', $departIds] ]; $field = 'fences.id, name, fence_shape as shape,fences.creator_id as userid, is_check_in as inFenceAlarm,fence_type, is_check_out as outFenceAlarm, fence_info as fenceInfo, departments.department_name'; $res = M('fences')->field($field) ->join('departments on fences.departments = departments.id') ->where($fenceCond) ->select(); if(!$res){ json_fail('查询不到系统围栏'); } foreach($res as &$v){ $v['inFenceAlarm'] = (bool)($v['inFenceAlarm']); $v['outFenceAlarm'] = (bool)($v['inFenceAlarm']); $v['fence_type_text'] = $fenceTypeAssoc[$v['fence_type']]; } json_success('查询成功', $res); } public function userUnbindDevice( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } // 通过手机号和短信验证码注册 $data = json_decode( file_get_contents("php://input") ,true); //$data['imei'],$data['user_no'],$data['username'] //先查询设备信息 看是否被绑定 if(!$data['device_id']){ json_fail('缺少设备ID参数'); } $device_info=M('devices')->where(array('id'=>$data['device_id']))->find(); if(!$device_info){ json_fail('设备不存在,请确认输入无误'); } $save_data=array( 'user_id'=>'', 'badge_user_id'=>'', 'use_state'=>0, ); M()->startTrans(); if($device_info['badge_user_id']){ $badRes=M('badgeuser')->createSave(array('id'=>$device_info['badge_user_id']),array('is_used'=>0)); if(!$badRes){ json_fail('解绑失败'); } } $devRes=M('devices')->createSave(array('id'=>$device_info['id']),$save_data); if(!$devRes){ M()->rollback(); json_fail('解绑失败'); } // 如果没有设备了,置空 department_id if (!M('devices')->where(['user_id'=>$userid])->count()) { $res = M('users')->where(['id'=>$userid])->setField(['department_id'=>'']); if($res === false){ M()->rollback(); json_fail('解绑失败2'); } } M()->commit(); json_success('解绑成功',$userid); } public function addUserFence( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $data = json_decode( file_get_contents("php://input") ,true); $userid =intval($data['userid']); if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } $fenceName = $data['fenceName']; if(!$fenceName){ json_fail('获取不到围栏名'); } $fenceInfo = $data['fenceInfo']; if(!$fenceInfo){ json_fail('获取不到围栏信息'); } $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($fenceInfo['center']['lat'], $fenceInfo['center']['lng']); $fenceInfo['center']['lat'] = $convPoint['lat']; $fenceInfo['center']['lng'] = $convPoint['lng']; $saveData = [ 'creator_id' => $userid, 'name' => $fenceName, 'push_users' => json_encode([$userid]), 'fence_shape' => 'circle', 'fence_type' => 1, 'fence_info' => json_encode($fenceInfo), 'created_at' => time(), 'created_at' => time() ]; $res = M('fences')->add($saveData); if(!$res){ json_fail('保存入库失败'); } json_success('保存入库成功'); } private function getWeixinAccessToken( ){ $token = (new \Jiaruan\WxTmp())->getAccessToken(); return $token; /* $appid= C('WECHAT_APPID'); $appSecret = C('WECHAT_APPSECRET'); $accessToken = S('wx_pub_accessToken'); if(!$accessToken){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appSecret); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = json_decode(curl_exec($ch), true); curl_close($ch); if($output['errcode']){ return $output; } S('wx_pub_accessToken', $output['access_token'], '7100'); return $output['access_token']; }else{ return $accessToken; } */ } public function getAlarmRecords( ){ header('Access-Control-Allow-Origin: *'); $post_data = json_decode(file_get_contents('php://input'), true); $openid = $post_data['openid']; $userid = $post_data['userid']; //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } // 获取登录账号部门下所有告警状态的学生数据 $user_model = M('users'); $where = ['id' => $userid]; $userinfo = $user_model->field('id,department_id')->where($where)->find(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取数据失败'); } $limit = isset($post_data['limit']) ? $post_data['limit'] : 10; $page = isset($post_data['page']) ? $post_data['page'] : 1; // 告警记录条件 // 初始化条件 $cond = []; $reason = I('get.reason'); $state = I('get.state'); $result = I('get.result'); if ($reason) { if ($reason == 'fence') { $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out']]; } else { $cond['alarm_reason'] = $reason; } } else { // 默认只显示 SOS 和围栏告警记录 $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out', 'press']]; } if ($state) { $cond['state'] = $state; } if ($result !== '' && is_numeric($result)) { $cond['result'] = $result; } if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } // 查出总数量 $list = []; $total = M('alarm_records')->where($cond)->count(); if ($total) { if ($state == 'start' || $state == 'end') { $order = "{$state}_time desc"; } else { $order = 'id desc'; } $fields = 'id,device_number,alarm_reason,handler_id,start_time,end_time,state,comment,result'; $list = M('alarm_records')->field($fields)->where($cond)->limit($limit)->page($page)->order($order)->select() ?: []; if (!empty($list)) { // alarm_reason,handler_id,result // 获取告警类型 $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id'); $reason_arr = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value'); // 处理结果 $result_arr = [ 0 => '待处理', 1 => '已处理', 2 => '误报', ]; // 中文转换 foreach ($list as &$alarm) { $alarm['start_time'] = $alarm['start_time'] ? date('Y-m-d H:i:s', $alarm['start_time']) : ''; $alarm['end_time'] = $alarm['end_time'] ? date('Y-m-d H:i:s', $alarm['end_time']) : ''; if (is_array($reason_arr)) { $alarm['alarm_reason'] = $reason_arr[$alarm['alarm_reason']]; } if (is_numeric($alarm['result'])) { $alarm['result'] = $result_arr[$alarm['result']]; } } } } // 返回 $data = [ 'total' => $total, 'limit' => $limit, 'page' => $page, 'list' => $list, ]; json_success('获取成功', $data); } public function getAlarmDetail( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $alarm_id = I('get.id'); if (!$alarm_id) { json_fail('获取告警信息失败1'); } // 查出告警数据 $where = ['id' => $alarm_id]; $alarm_info = M('alarm_records')->where($where)->find(); if (empty($alarm_info)) { json_fail('获取告警信息失败2'); } $report_id = I('get.rid'); if (!$report_id) { json_fail('获取告警信息失败3'); } $where = ['id' => $report_id]; $alarm_report = M('alarm_report')->where($where)->find(); if (empty($alarm_report)) { json_fail('获取告警信息失败4'); } $alarm_info['address']=$alarm_report['address']; // 查出设备信息 $where = ['imei' => $alarm_info['device_number']]; $device_info = M('devices')->where($where)->find(); if (empty($alarm_info)) { json_fail('获取告警设备信息失败'); } if ($device_info['online_time'] > $device_info['wifi_online_time']) { $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']); $device_info['last_location'] = $device_info['longitude'] .','. $device_info['latitude']; $res = bmap_geocoding($device_info['latitude'], $device_info['longitude']); if($res['success']){ $device_info['address'] = $res['address']; }else{ $device_info['address']=''; } } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) { $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']); $device_info['last_location'] = $device_info['wifi_longitude'] .','. $device_info['wifi_latitude']; } else { $device_info['last_online_time'] = '0000-00-00 00:00:00'; $device_info['last_location'] = ''; $device_info['address']=''; } // 查出设备用户 if ($device_info['badge_user_id']) { $where = ['id' => $device_info['badge_user_id']]; $user_info = M('badgeuser')->where($where)->find() ?: []; } else { $where = ['id' => $device_info['user_id']]; $user_info = M('users')->where($where)->find() ?: []; } //if (empty($user_info)) { //json_fail('获取告警用户信息失败'); //} // 获取紧急联系人 $where = ['device_id' => $device_info['id']]; $urgent_list = M('kq_urgent')->where($where)->select() ? : []; if (!empty($urgent_list)) { $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id'); $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value'); foreach ($urgent_list as $key => &$urgent) { $urgent['relationship_text'] = $ships[$urgent['relationship']]; } } // 部门名称 $alarm_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name'); $alarm_info['user_info'] = $user_info; $alarm_info['urgent_list'] = $urgent_list; $alarm_info['device_info'] = $device_info; $alarm_info['device_info']['department_name'] = $alarm_info['department_name']; json_success('获取成功', $alarm_info); } public function handleAlarm( ){ header('Access-Control-Allow-Origin: *'); $post_data = json_decode(file_get_contents('php://input'), true); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } // result 1-出警,2-误报 if (!$post_data['result']) { json_fail('处理结果不能为空'); } if (!$post_data['comment']) { json_fail('处理原因不能为空'); } if (!$post_data['id']) { json_fail('未获取到告警信息1'); } $time = time(); M()->startTrans(); // 修改前,检测结果是否一致,如果一致不允许重复操作 $records_model = M('alarm_records'); $where = ['id' => $post_data['id']]; $record_info = $records_model->where($where)->field('device_number,result')->find(); if (empty($record_info)) { json_fail('未获取到告警信息2'); } //if ($record_info['result'] > 0) { if ($record_info['result'] == $post_data['result']) { M()->rollback(); json_fail('已处理,请勿重复操作'); } $where = ['id' => $post_data['id']]; $save_data = [ 'comment' => $post_data['comment'], 'result' => $post_data['result'], 'handler_id' => $userid, 'state' => 'end', 'end_time' => $time, 'updated_at' => $time, ]; $res = $records_model->createSave($where, $save_data); if ($res === false) { M()->rollback(); json_fail('操作失败'); } // 查出设备告警状态 $where = ['imei' => $record_info['device_number']]; $device_info = M('devices')->where($where)->field('id,alarm_state')->find(); if ($device_info['alarm_state'] > 0) { // 修改设备状态 $where = ['id' => $device_info['id']]; $res = M('devices')->where($where)->setField('alarm_state', 0); if (!$res) { M()->rollback(); json_fail('修改设备状态失败'); } } M()->commit(); json_success('操作成功'); } public function editYysProfile( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $data = json_decode( file_get_contents("php://input") ,true); $data = array_map(function($item){ return trim($item); }, $data); if (!$data['nickName']) { json_fail('昵称不能为空'); } if (!$data['phone']) { json_fail('手机号码不能为空'); } if (!preg_match('/^[-_a-zA-Z0-9]{6,16}?$/', $data['phone'])) { json_fail('手机号码格式不正确'); } // 修改密码 if ($data['oldPwd']) { if (!$data['newPwd']) { json_fail('新密码不能为空'); } if (!$data['confirmNewPwd']) { json_fail('确认密码不能为空'); } if ($data['newPwd'] != $data['confirmNewPwd']) { json_fail('两次新密码不一致'); } } $userCond = array( 'id' => $userid); $user_info = M('users')->where($userCond)->find(); if(!$user_info){ json_fail('获取用户信息失败'); } if ($user_info['wx_open_id'] != $openid) { json_fail('账号可能被其他用户登录,请重新登录'); } if ($data['oldPwd']) { if(!password_verify($data['oldPwd'], $user_info['password'])){ json_fail('原密码不正确'); } } $saveData = [ 'realname' => $data['nickName'], 'phone' => $data['phone'], ]; // 有原密码才能修改 if ($data['oldPwd']) { $saveData['password'] = password_hash($data['newPwd'], PASSWORD_DEFAULT); } $result = M('users')->createSave($userCond, $saveData); if(!$result){ json_fail('修改失败'); } $respData = [ 'id' => $user_info['id'], 'realname' => $data['nickName'], 'avatar' => $user_info['avatar'], 'phone' => $data['phone'], ]; json_success('修改成功', $respData); } public function changeAuthorize( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $imei = I('get.imei'); if(!$imei){ json_fail('获取不到设备号'); } $authorize = intval(I('get.authorize') ); if($authorize !== 0 && $authorize !== 1){ json_fail('授权状态值不合法'); } $saveData = [ 'authorize' => $authorize, 'updated_at' => time() ]; $res = M('devices')->where(['imei' => $imei])->save($saveData); if(!res){ json_fail('权限修改失败'); } json_success('权限修改成功'); } public function getDeviceInfoSingle( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $imei = I('get.imei'); if(!$imei){ json_fail('获取不到设备号'); } $res = M('devices')->where(['imei' => $imei])->find(); if(!res){ json_fail('获取设备信息失败'); } json_success('获取设备信息成功', $res); } public function getDevices( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } // 获取 POST 数据 $post_data = json_decode(file_get_contents('php://input'), true); $limit = isset($post_data['limit']) ? $post_data['limit'] : 10; $page = isset($post_data['page']) ? $post_data['page'] : 1; $imei = $post_data['imei']; $list = []; $cond = []; $devices_model = M('devices'); // 查出总数量 if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } if ($imei) { $cond['imei'] = ['LIKE', "%{$imei}%"]; } $total = $devices_model->where($cond)->count(); if ($total) { $list = $devices_model->where($cond)->limit($limit)->page($page)->select() ?: []; } // 返回 $data = [ 'total' => $total, 'limit' => $limit, 'page' => $page, 'list' => $list, ]; json_success('获取成功', $data); } private function getYysLoginUserinfo( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); if(!$openid){ json_fail('未获取到微信授权信息,请重新点击菜单进入并授权'); } // 微信运营角色 $where = ['identify' => 'wxyy']; $role_id = M('roles')->where($where)->getField('id'); if (!$role_id) { json_fail('未开放微信运营角色'); } // 获取登录账号信息 $userid = I('get.userid'); $cond = [ //'u.wx_open_id' => $openid, 'u.id' => $userid, ]; //$userinfo = M('users')->field('id,department_id')->where($where)->find(); $userinfo = M('users')->alias('u')->field('u.*')->where($cond)->join("INNER JOIN user_has_roles AS r ON u.id = r.uid AND r.role_id = {$role_id}")->find(); if (!$userinfo) { json_fail('获取用户信息失败,请重新登录'); } if ($userinfo['wx_open_id'] != $openid) { json_fail('账号可能在其他设备登录,请重新登录'); } return $userinfo; } public function getDeviceDetail( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('未获取到用户标识,请重新登陆'); } $id = I('get.id'); if (!$id) { json_fail('获取设备信息失败'); } $openid = I('get.openid'); //检测登录状态 $res = $this->checkLoginState($openid, $userid); if(!$res['status']){ json_fail($res['message']); } // 检测是否在查询权限范围 // 查出设备信息 $where = ['id' => $id]; $device_info = M('devices')->where($where)->find() ? : []; if (empty($device_info)) { json_fail('未获取到设备信息'); } if ($device_info['online_time'] >= $device_info['wifi_online_time']) { $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']); $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($device_info['latitude'],$device_info['longitude']); $device_info['last_location'] = $convPoint['lng'] .','. $convPoint['lat']; } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) { $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']); $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($device_info['wifi_latitude'],$device_info['wifi_longitude']); $device_info['last_location'] = $convPoint['lng'] .','. $convPoint['lat']; } else { $device_info['last_online_time'] = '0000-00-00 00:00:00'; $device_info['last_location'] = ''; } // 查出设备用户 if ($device_info['badge_user_id']) { $where = ['id' => $device_info['badge_user_id']]; $user_info = M('badgeuser')->where($where)->find() ?: []; } else { $where = ['id' => $device_info['user_id']]; $user_info = M('users')->where($where)->find() ?: []; } //if (empty($user_info)) { //json_fail('获取告警用户信息失败'); //} // 获取紧急联系人 $where = ['device_id' => $device_info['id']]; $urgent_list = M('kq_urgent')->where($where)->select() ? : []; if (!empty($urgent_list)) { $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id'); $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value'); foreach ($urgent_list as $key => &$urgent) { $urgent['relationship_text'] = $ships[$urgent['relationship']]; } } // 部门名称 $device_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name'); $device_info['user_info'] = $user_info; $device_info['urgent_list'] = $urgent_list; json_success('获取成功', $device_info); } public function getWaitHandleAlarmCounts( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } $cond = [ 'state' => 'start', ]; // 查出总数量 if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } $fields = 'alarm_reason, count(alarm_reason) as count'; $list = M('alarm_records')->where($cond)->group('alarm_reason')->getField($fields) ?:[]; json_success('获取成功', $list); } public function getDevicePositionList( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } $cond = [ 'use_state' => 1, ]; // 查出总数量 if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } $fields = 'imei,device_name,device_type,battery_level,loc_mode,loc_ploy,online_time,longitude,latitude,wifi_online_time,wifi_longitude,wifi_latitude,alarm_state'; $list = M('devices')->field($fields)->where($cond)->select() ?: []; $resp = []; foreach($list as &$locationInfo){ //new end //wifi_online_time //wifi_longitude //wifi_latitude //addr $locationInfo['isAlarm'] = $locationInfo['alarm_state']; $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ; $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time']; $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude']; $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude']; if(!$locationInfo['time']){ $locationInfo['awayTime'] = '从未在线'; }else{ $timeInterval = time() - (int)$locationInfo['time']; $locationInfo['awayTime'] = $this->getHumenTime($timeInterval); } $lngLatAlter = new \Jms\Algo\Geometry(); if(!$locationInfo['lat'] || !$locationInfo['lng']){ continue; } $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']); $locationInfo['lat'] = $latLng['lat']; $locationInfo['lng'] = $latLng['lng']; $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']); array_push($resp, $locationInfo); } json_success('获取成功', $resp); } public function getAllFences( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $userid =intval(I('get.userid')); if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } $field = 'id, name, fence_shape as shape, creator_id as userid, is_check_in as inAlarm, is_check_out as outAlarm, fence_info as info'; $cond = [ 'fence_type' => 0, 'creator_id' => $userid, '_logic' => 'OR' ]; $res = M('fences')->field($field)->where($cond)->select(); if(!$res){ json_fail('查询不到可见的围栏'); } foreach($res as &$v){ $v['inAlarm'] = (bool)($v['inAlarm']); $v['outAlarm'] = (bool)($v['outAlarm']); $v['info'] = json_decode($v['info'], true); } json_success('查询成功', $res); } public function editUserFence( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $data = json_decode( file_get_contents("php://input") ,true); $userid =intval($data['userid']); if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } $fenceId = intval($data['fenceId']); $fenceName = $data['fenceName']; if(!$fenceName){ json_fail('获取不到围栏名'); } $fenceInfo = $data['fenceInfo']; if(!$fenceInfo){ json_fail('获取不到围栏信息'); } $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($fenceInfo['center']['lat'], $fenceInfo['center']['lng']); $fenceInfo['center']['lat'] = $convPoint['lat']; $fenceInfo['center']['lng'] = $convPoint['lng']; $saveData = [ 'name' => $fenceName, 'fence_shape' => 'circle', 'fence_info' => json_encode($fenceInfo), 'updated_at' => time() ]; $res = M('fences')->where(['id' => $fenceId])->save($saveData); if(!$res){ json_fail('保存入库失败'); } json_success('保存入库成功'); } public function getRelationshipList( ){ header('Access-Control-Allow-Origin: *'); // 查出 Relationships id $where = array('code' => 'Relationships'); $type_id = M('sys_dict_type')->where($where)->getField('id'); if (empty($type_id)) { json_fail('获取失败'); } $where = array('type_id' => $type_id); $list = M('sys_dict_data')->field('code as id, value as text')->where($where)->select(); if (empty($list)) { json_fail('获取失败'); } json_success('获取成功', $list); } public function addEditUrgent( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $post_data = file_get_contents('php://input'); $post_data = json_decode($post_data, true); $userid = $post_data['userid']; $name = $post_data['name']; $phone = $post_data['phone']; $relationship = $post_data['relationship']; $device_id = $post_data['device_id']; $id = $post_data['id']; if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } if(!$device_id){ json_fail('获取设备信息失败'); } if(!$name || !$phone || !$relationship){ json_fail('紧急联系人姓名、电话和社会关系不能为空'); } if ($id) { $saveData = [ 'name' => $name, 'phone' => $phone, 'relationship' => $relationship, 'device_id' => $device_id, ]; $res = M('kq_urgent')->createSave(['id'=>$id], $saveData); if($res === false){ json_fail('修改失败'); } json_success('修改成功'); } $saveData = [ 'name' => $name, 'phone' => $phone, 'relationship' => $relationship, 'creator_id' => $userid, 'created_at' => time(), 'device_id' => $device_id, ]; $res = M('kq_urgent')->createAdd($saveData); if($res === false){ json_fail('添加失败'); } json_success('添加成功'); } public function getUrgentById( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } $id = I('get.id'); if(!$id){ json_fail('获取信息失败'); } $where = array('id'=>$id); $res = M('kq_urgent')->where($where)->find(); if($res === false){ json_fail('获取失败'); } json_success('获取成功', $res); } public function deleteUrgent( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid){ json_fail('获取不到你的用户标识,请重新登陆'); } $id = I('get.id'); if(!$id){ json_fail('获取信息失败'); } $device_id = I('get.device_id'); $where = array('id'=>$id, 'device_id'=>$device_id); $res = M('kq_urgent')->where($where)->delete(); if($res === false){ json_fail('删除失败'); } json_success('删除成功', $res); } public function editProfile( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $data = json_decode( file_get_contents("php://input") ,true); $data = array_map(function($item){ return trim($item); }, $data); if (!$data['nickName']) { json_fail('昵称不能为空'); } if (!$data['phone']) { json_fail('手机号码不能为空'); } else { if (!preg_match('/^[-_a-zA-Z0-9]{6,16}?$/', $data['phone'])) { json_fail('手机号码格式不正确'); } } // 修改密码 if ($data['oldPwd']) { if (!$data['newPwd']) { json_fail('新密码不能为空'); } if (!$data['confirmNewPwd']) { json_fail('确认密码不能为空'); } if ($data['newPwd'] != $data['confirmNewPwd']) { json_fail('两次新密码不一致'); } } $userCond = array( 'id' => $userid); $user_info = M('users')->where($userCond)->find(); if(!$user_info){ json_fail('获取用户信息失败'); } if ($user_info['wx_open_id'] != $openid) { json_fail('账号可能被其他用户登录,请重新登录'); } if ($data['oldPwd']) { if(!password_verify($data['oldPwd'], $user_info['password'])){ json_fail('原密码不正确'); } } $saveData = [ 'realname' => $data['nickName'], 'phone' => $data['phone'], ]; // 有原密码才能修改 if ($data['oldPwd']) { $saveData['password'] = password_hash($data['newPwd'], PASSWORD_DEFAULT); } $result = M('users')->createSave($userCond, $saveData); if(!$result){ json_fail('修改失败'); } $respData = [ 'id' => $user_info['id'], 'realname' => $data['nickName'], 'avatar' => $user_info['avatar'], 'phone' => $data['phone'], ]; json_success('修改成功', $respData); } public function getNewsDetail( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } $openid = I('get.openid'); $id = I('get.id'); if (!$id) { json_fail('缺少参数:id'); } //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $cond = ['id' => $id]; $info = M('news')->where($cond)->find(); if (empty($info)) { json_fail('获取信息失败'); } json_success('获取成功', $info); } public function getActivityDetail( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $id = I('get.id'); if (!$id) { json_fail('缺少参数:id'); } // 获取详情 $info = M('activity')->where(['id' => $id])->find(); if (empty($info)) { json_fail('未获取到活动信息'); } $info['updated_at_datetime'] = date('Y-m-d H:i:s',$info['updated_at']); $info['start_time'] = date('Y-m-d H:i:s',$info['start_time']); $info['end_time'] = date('Y-m-d H:i:s',$info['end_time']); $info['creator'] = M('users')->where(['id' => $info['creator_id'] ])->getField('username') ? : 'admin'; // 获取报名用户数量 $applyCount = M('activity_has_users')->where(['activity_id' => $id])->count(); $info['apply_count'] = $applyCount ? $applyCount : 0; // 该用户报名状态 $where = ['activity_id' => $id, 'user_id' => $userid]; $info['apply_status'] = M('activity_has_users')->where($where)->find() ? 1 : 0; json_success('获取成功', $info); } public function applyActivity( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $post_data = json_decode(file_get_contents('php://input'), true); if (!$post_data['id']) { json_fail('未获取到报名活动'); } $courses_model = M('activity'); $apply_users_model = M('activity_has_users'); // 检测课程是否发布 $where = ['id' => $post_data['id']]; $publish = $courses_model->where($where)->getField('status'); if (!$publish) { json_fail('活动不存在或未发布'); } // 获取设备信息 $where = ['id' => $userid]; $user_info = M('users')->where($where)->find(); if (empty($user_info)) { json_fail('获取报名用户信息失败'); } // 检测是否已报名 // $apply_user_id = $device_info['badge_user_id'] ? : $device_info['user_id']; $apply_user_id = $userid; $where = ['user_id' => $apply_user_id, 'activity_id' => $post_data['id']]; if ($apply_users_model->where($where)->count()) { json_fail('已报名,请勿重复操作'); } $time = time(); $save_data = [ 'activity_id' => $post_data['id'], 'user_id'=> $apply_user_id, 'apply_time'=> $time, 'department_id' => $user_info['department_id'], 'creator_id' => $userid, 'created_at' => $time, ]; $res = $apply_users_model->createAdd($save_data); if (!$res) { json_fail('报名失败,请稍后重试'); } json_success('报名成功'); } public function getLastPositionSingle( ){ header('Access-Control-Allow-Origin: *'); $imei = I('get.imei'); if(!$imei){ json_fail('服务端未检测到设备编号'); } $locationInfo = M('devices')->where(['imei' => $imei])->find(); if(!$locationInfo){ json_fail('查询不到该设备当前信息哦!'); } //new start $isThirdParty = M('third_party_devices')->where(['device_imei' => $locationInfo['imei']])->count(); if($isThirdParty){ $thindLoc = $this->getThirdLocation($locationInfo['imei']); if($thindLoc){ $locationInfo['lng'] = $thindLoc['lon']; $locationInfo['lat'] = $thindLoc['lat']; $locationInfo['time'] = $thindLoc['receiveAt']; } } //new end //wifi_online_time //wifi_longitude //wifi_latitude //addr $locationInfo['isAlarm'] = $locationInfo['alarm_status']; $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ;; $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time']; $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude']; $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude']; if(!$isThirdParty){ $locationInfo['address'] = $locationInfo['address']; } // if(!$locationInfo['time']){ $locationInfo['awayTime'] = '从未在线'; }else{ $timeInterval = time() - (int)$locationInfo['time']; $locationInfo['awayTime'] = $this->getHumenTime($timeInterval); } $lngLatAlter = new \Jms\Algo\Geometry(); if($isThirdParty){ $latLng = $lngLatAlter->wgsTOgcj($locationInfo['lat'], $locationInfo['lng']); $locationInfo['lat'] = $latLng['lat']; $locationInfo['lng'] = $latLng['lng']; }else{ $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']); $locationInfo['lat'] = $latLng['lat']; $locationInfo['lng'] = $latLng['lng']; } $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']); json_success('查询成功', $locationInfo); } public function yysLogin( ){ header('Access-Control-Allow-Origin: *'); //json_fail('登录失败'); $openid = I('get.openid'); if(!$openid){ json_fail('未授权,请关闭当前页面重新进入'); } $data = json_decode( file_get_contents("php://input") ,true); // 微信运营角色 $where = ['identify' => 'wxyy']; $role_id = M('roles')->where($where)->getField('id'); if (!$role_id) { json_fail('未开放微信运营角色'); } $cond = array( 'username' => $data['username'], ); $user_info = M('users')->alias('u')->where($cond)->join("INNER JOIN user_has_roles AS r ON u.id = r.uid AND r.role_id = {$role_id}")->find(); if(!$user_info){ json_fail('无登录权限或账号、密码错误'); } if(!password_verify($data['password'], $user_info['password'])){ json_fail('账号或密码错误'); } if($user_info['wx_open_id'] != $openid){ $update = array( 'wx_open_id' => $openid, 'last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_time' => time(), ); $result = M('users')->createSave(array('id'=>$user_info['uid']),$update); if(!$result){ json_fail('登陆失败'); } } //如果当前openid与其他账号openid相同,清空其他表中openid /* $where = array( 'wx_open_id' => $openid, 'id' => ['NEQ', $user_info['id']], ); $result = M('users')->createSave($where,['wx_open_id'=>'']); if(!$result){ json_fail('登陆失败'); } */ $res = array( 'id'=>$user_info['uid'], 'realname'=>$user_info['realname'], 'avatar' => $user_info['avatar'], 'phone'=>$user_info['phone'], ); json_success('登录成功', $res); } public function getSlider( ){ header('Access-Control-Allow-Origin: *'); //json_fail('登录失败'); $openid = I('get.openid'); if(!$openid){ json_fail('用户未授权'); } $cond = array( 'is_enable'=>1 ); $list = M('banner')->where($cond)->select(); if(!$list){ $list = [ ['banner_url' => 'https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/no_banner.jpg'] ]; } json_success('获取成功',$list); } public function getWaitHandleAlarmData( ){ header('Access-Control-Allow-Origin: *'); $post_data = json_decode(file_get_contents('php://input'), true); $openid = $post_data['openid']; $userid = $post_data['userid']; //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } // 获取登录账号部门下所有告警状态的学生数据 $user_model = M('users'); $where = ['id' => $userid]; $userinfo = $user_model->field('id,department_id')->where($where)->find(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取数据失败'); } $limit = isset($post_data['limit']) ? $post_data['limit'] : 10; $page = isset($post_data['page']) ? $post_data['page'] : 1; // 查出告警学生id $cond = [ 'alarm_status' => 1, ]; if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } // 查出总数量 $student_list = []; $total = $user_model->where($cond)->count(); if ($total) { $fields = 'id,avatar,realname,sex,age,active_rfid,student_no,online_time,last_station_mac,longitude,latitude'; $student_list = $user_model->field($fields)->where($cond)->limit($post_data['limit'])->page($post_data['page'])->select() ?: []; } // 返回 $data = [ 'total' => $total, 'limit' => $limit, 'page' => $page, 'list' => $student_list, ]; json_success('获取成功', $data); } private function getRightCreatorIds( $userinfo ){ $uid = $userinfo['id']; $dept_id = $userinfo['department_id']; // 非系统角色 $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']]; $devides_user_ids = M('roles')->where($where)->getField('id', true); // 查出拥有系统角色 $where = [ 'uid' => $uid, 'role_id' => ['NOT IN', $devides_user_ids], ]; $role_ids = M('user_has_roles')->where($where)->getField('role_id', true); if (empty($role_ids)) { return false; } $user_ids = []; $is_all = false; // 全部数据 // 查出角色拥有权限 $where = ['id' => ['IN', $role_ids]]; $range_list = M('roles')->distinct(true)->where($where)->getField('data_range', true); if (empty($range_list)) { return false; } // 根据角色权限查出 $depart_model = M('departments'); foreach($range_list as $range) { switch ($range) { case '1': // 全部数据 $is_all = true; break; case '2': // 自定义数据 case '3': // 本人数据 $user_ids[] = $uid; break; case '4': // 部门数据 $user_ids = array_merge($user_ids, $this->getUserIdsByDepartmentId([$dept_id])); break; case '5': // 部门及以下数据 // 查一下下级部门 // REGEXP '(^76$)|(^76-)' //$departmentIds = $depart_model->where(['parent_id' => $dept_id])->getField('id', true); $cond = ['level' => ['EXP',"REGEXP '(^{$dept_id}$)|(^{$dept_id}-)'"]]; $departmentIds = $depart_model->where($cond)->getField('id', true) ?: []; $departmentIds[] = $dept_id; $user_ids = array_merge([$uid], $this->getUserIdsByDepartmentId($departmentIds)); break; default: break; } // 如果有全部数据 直接跳出 if ($is_all) { break; } } if ($is_all) { return true; } return array_unique(array_filter($user_ids)); } private function getUserIdsByDepartmentId( $id ){ // 取出非设备用户 (roles identify not in 'personal,group_badge_user,group_card_user') $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']]; $devide_role_ids = M('roles')->where($where)->getField('id', true); $devide_role_ids = join(',', $devide_role_ids); $cond = [ 'u.department_id' => ['IN', $id], ]; $ids = M('users')->alias('u') ->field('u.id') ->where($cond) ->join("INNER JOIN user_has_roles r ON u.id=r.uid AND r.role_id NOT IN ({$devide_role_ids})") ->select() ? : []; return array_unique(array_column($ids, 'id')); } public function getConfirmAlarmData( ){ header('Access-Control-Allow-Origin: *'); $post_data = json_decode(file_get_contents('php://input'), true); $openid = $post_data['openid']; if(!$openid){ json_fail('未获取到微信授权信息,请重新点击菜单进入并授权'); } $limit = isset($post_data['limit']) ? $post_data['limit'] : 10; $page = isset($post_data['page']) ? $post_data['page'] : 1; // 获取登录账号部门下所有告警状态的学生数据 $where = ['wx_open_id' => $openid]; $userinfo = M('users')->field('id,department_id')->where($where)->find(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } // 查出告警学生id $cond = [ 'result' => 1, ]; if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } // 查出总数量 $record_list = []; $alarm_handle_records_model = M('alarm_handle_records'); $total = $alarm_handle_records_model->where($cond)->count(); if ($total) { $record_list = $alarm_handle_records_model->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: []; } // 返回 $data = [ 'total' => $total, 'limit' => $limit, 'page' => $page, 'list' => $record_list, ]; json_success('获取成功', $data); } public function getCancelAlarmData( ){ header('Access-Control-Allow-Origin: *'); $post_data = json_decode(file_get_contents('php://input'), true); $openid = $post_data['openid']; if(!$openid){ json_fail('未获取到微信授权信息,请重新点击菜单进入并授权'); } $limit = isset($post_data['limit']) ? $post_data['limit'] : 10; $page = isset($post_data['page']) ? $post_data['page'] : 1; // 获取登录账号部门下所有告警状态的学生数据 $where = ['wx_open_id' => $openid]; $userinfo = M('users')->field('id,department_id')->where($where)->find(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } // 查出告警学生id $cond = [ 'result' => 2, ]; if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } // 查出总数量 $record_list = []; $alarm_handle_records_model = M('alarm_handle_records'); $total = $alarm_handle_records_model->where($cond)->count(); if ($total) { $record_list = $alarm_handle_records_model->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: []; } // 返回 $data = [ 'total' => $total, 'limit' => $limit, 'page' => $page, 'list' => $record_list, ]; json_success('获取成功', $data); } public function getFenceAlarmData( ){ header('Access-Control-Allow-Origin: *'); $post_data = json_decode(file_get_contents('php://input'), true); $openid = $post_data['openid']; if(!$openid){ json_fail('未获取到微信授权信息,请重新点击菜单进入并授权'); } $limit = isset($post_data['limit']) ? $post_data['limit'] : 10; $page = isset($post_data['page']) ? $post_data['page'] : 1; // 获取登录账号部门下所有告警状态的学生数据 $where = ['wx_open_id' => $openid]; $userinfo = M('users')->field('id,department_id')->where($where)->find(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } // 查出围栏 $cond = []; if (!$post_data['type']) { $cond['alarm_type'] = ['IN',['fence_in','fence_out']]; } elseif ($post_data['type'] == 'in') { $cond['alarm_type'] = 'fence_in'; } elseif ($post_data['type'] == 'out') { $cond['alarm_type'] = 'fence_out'; } else { json_fail('未知的围栏类型'); } if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } // 查出总数量 $list = []; $alarm_report = M('alarm_report'); $total = $alarm_report->where($cond)->count(); if ($total) { $list = $alarm_report->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: []; } // 返回 $data = [ 'total' => $total, 'limit' => $limit, 'page' => $page, 'list' => $list, ]; json_success('获取成功', $data); } public function getYysFences( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } $fence_type = I('get.type'); if (!$fence_type && $fence_type !== 0 && $fence_type !== '0') { json_fail('未获取到围栏类型'); } $cond = [ 'fence_type' => $fence_type, ]; // 查出总数量 if (is_array($creator_ids)) { $cond['creator_id'] = ['IN', $creator_ids]; } $field = 'id, name, fence_shape as shape, creator_id as userid, is_check_in as inAlarm, is_check_out as outAlarm, fence_info as fenceInfo'; $list = M('fences')->field($field)->where($cond)->select(); if(!$list){ json_fail('暂无围栏'); } $geometry = new \Jms\Algo\Geometry(); foreach($list as &$v){ $v['inAlarm'] = (bool)($v['inAlarm']); $v['outAlarm'] = (bool)($v['outAlarm']); // 坐标转换:GCJ-02 -> BD-09 $v['fenceInfo'] = json_decode($v['fenceInfo'], true) ?:[]; $convPoint = $geometry->convertBd09ToGcj02($v['fenceInfo']['center']['lat'], $v['fenceInfo']['center']['lng']); $v['fenceInfo']['center']['lat'] = $convPoint['lat']; $v['fenceInfo']['center']['lng'] = $convPoint['lng']; } json_success('获取成功', $list); } public function recorder_wxfunc( ){ header('Access-Control-Allow-Origin: *'); $action = I('post.action'); if($action === 'sign'){ $url=I('post.url'); $res = $this->getRecSignature($url); echo json_encode($res); } if($action === 'wxdown'){ $mediaId = I('post.mediaID'); $res = $this->getWxRecByMid($mediaId); // echo json_encode(['c' => 0]); echo json_encode($res); } } private function getRecSignature( $url ){ header('Access-Control-Allow-Origin: *'); $url = urldecode($url); $accessToken = $this->getWeixinAccessToken(); if (!$accessToken) { return [ 'c' => 99, 'm' => '获取微信accesstoken失败' ]; } $apiTiket = $this->getJsapiTikcet($accessToken); if(is_array($apiTiket)){ json_fail($apiTiket['errcode'].':'.$apiTiket['errmsg']); return [ 'c' => $apiTiket['errcode'], 'm' => $apiTiket['errmsg'] ]; } $noncestr = substr(md5(time()), 0, 16); $timestamp = time(); //jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value $str = 'jsapi_ticket='.$apiTiket.'&noncestr='.$noncestr.'×tamp='.$timestamp.'&url='.$url; $signature = sha1($str); return [ 'c' => 0, 'm' => '', 'v' => [ 'appid' => C('WECHAT_APPID'), 'timestamp' => $timestamp, 'noncestr' => $noncestr, 'signature' => $signature, ] ]; } public function addEditFence( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); $id = I('get.id'); $data = json_decode( file_get_contents("php://input") ,true) ?: []; // 围栏类型 $fenceTypeArr = [ 'inout' => 0, // 机构安全围栏 'person_inout' => 1, // 个人安全围栏 'sos' => 2, // SOS围栏 ]; if ($data['name']) { $data['name'] = trim($data['name']); } if ($data['fence_info']) { // 坐标转换:GCJ-02 -> BD-09 $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($data['fence_info']['center']['lat'], $data['fence_info']['center']['lng']); $data['fence_info']['center']['lat'] = $convPoint['lat']; $data['fence_info']['center']['lng'] = $convPoint['lng']; $data['fence_info'] = json_encode($data['fence_info']); } if ($data['in_fence_time_area'] && is_array($data['in_fence_time_area'])) { $data['in_fence_time_area'] = json_encode($data['in_fence_time_area']); } if ($data['out_fence_time_area'] && is_array($data['out_fence_time_area'])) { $data['out_fence_time_area'] = json_encode($data['out_fence_time_area']); } if ($data['push_users'] && is_array($data['push_users'])) { foreach($data['push_users'] as &$v){ $v = intval($v); } $data['push_users'] = json_encode($data['push_users']); } // 新增 if (!$id) { if($data['name'] === ''){ json_fail('围栏名称不能为空'); } if(!$data['fence_info']){ json_fail('未获取到围栏信息'); } if (!isset($fenceTypeArr[$data['fence_type']])) { json_fail('未知的围栏类型'); } $data['fence_shape'] = $data['fence_shape'] ?: 'circle'; $data['fence_type'] = $fenceTypeArr[$data['fence_type']]; $data['creator_id'] = $userinfo['id']; $data['departments'] = $userinfo['department_id']; $data['created_at'] = time(); $result = M('fences')->createAdd($data); if (!$result) { json_fail('添加失败'); } json_success('添加成功', $result); } // 修改 // 获取权限范围内的用户id $creatorIds = $this->getRightCreatorIds($userinfo); $info = M('fences')->where(['id'=>$id])->find(); if (empty($info)) { json_fail('获取围栏信息失败'); } if (!in_array($info['creator_id'], $creatorIds)) { //json_fail('无修改权限'); } unset($data['fence_type']); $cond = ['id'=>$id]; $result = M('fences')->createSave($cond, $data); if(!$result){ json_fail('保存失败'); } json_success('保存成功', $id); } public function deleteYysFences( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } $id = I('get.id'); if (!$id) { json_fail('参数不合法'); } $fence_info = M('fences')->where(['id'=>$id])->find(); if (!$fence_info) { json_fail('围栏不存在'); } if ($creator_ids !== true && !in_array($fence_info['creator_id'], $creator_ids)) { json_fail('无权限删除该围栏'); } $res = M('fences')->where(['id'=>$id])->delete(); if (!$res) { json_fail('删除失败'); } json_success('删除成功'); } public function getFenceInfo( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); $id = I('get.id'); if (!$id) { json_fail('缺少参数'); } $info = M('fences')->where(['id'=>$id])->find(); if(!$info){ json_fail('获取失败'); } // GCJ-02 -> BD-09 $info['fence_info'] = json_decode($info['fence_info'], true) ?: []; $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($info['fence_info']['center']['lat'], $info['fence_info']['center']['lng']); $info['fence_info']['center']['lat'] = $convPoint['lat']; $info['fence_info']['center']['lng'] = $convPoint['lng']; $info['in_fence_time_area'] = json_decode($info['in_fence_time_area'], true) ?: []; $info['out_fence_time_area'] = json_decode($info['out_fence_time_area'], true) ?: []; $info['push_users'] = json_decode($info['push_users'], true) ?: []; json_success('获取成功', $info); } private function getWxRecByMid( $mediaId ){ $accesstoken = $this->getWeixinAccessToken(); $url = 'https://api.weixin.qq.com/cgi-bin/media/get/jssdk?access_token='.$accesstoken.'&media_id='.$mediaId; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); //var_dump($decodeRes); //var_dump($output); //$output = json_decode(curl_exec($ch), true); curl_close($ch); $decodeRes = json_decode($output, true); if(is_array($decodeRes) && $decodeRes['errcode']){ return [ 'c' => $decodeRes['errcode'], 'm' => $decodeRes['errmsg'], ]; } $transformResPath = $this->wxSpeex2wav($output, $mediaId); $fileRes = file_get_contents($transformResPath); if($fileRes === false){ return [ 'c' => 91, 'm' => '音频转码失败', ]; } $duration = $this->getVoiceTime($transformResPath); unlink($transformResPath); return [ 'c' => 0, 'm' => '', 'v' => [ 'mime'=> 'audio/wav', 'data' => base64_encode($fileRes), 'duration' => $duration ] ]; } private function wxSpeex2wav( $audioContent, $mediaId ){ //$speex2wav = " speex2wav ".$file['storePath']."/a.speex ".$file['storePath']."/b.mp3"; $dirPath = realpath(__ROOT__).'/static/assets/wav/'.date('Ymd').'/transform_temp/'; if (!is_dir($dirPath)){ mkdir($dirPath,0777,true); } $speexPath = $dirPath . $mediaId . '.speex'; $fp = fopen($speexPath, 'a'); fwrite($fp, $audioContent); fclose($fp); $tempWavPath = $dirPath . $mediaId . "_temp.wav"; $cmd1 = " speex2wav ".$speexPath .' '. $tempWavPath; //$time = $this->getVoiceTime($uploadfile); exec($cmd1); $wavPath = $dirPath . $mediaId . ".wav"; $cmd2 = " ffmpeg -i ".$tempWavPath. " -b:a 128k -ar 8000 -ac 1 ". $wavPath; exec($cmd2); unlink($tempWavPath); unlink($speexPath); return $wavPath; } public function getFenceAlarmIntervals( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); $openid = I('get.openid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('未获取到用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid, $userid); if(!$res['status']){ json_fail($res['message']); } try { $typeid = M('sys_dict_type')->where(['code'=>'FenceSentInterval'])->getField('id'); $list = M('sys_dict_data')->field('value as text,code as value')->where(['type_id'=>$typeid])->select() ? : []; } catch (\Exception $e) { json_fail($e->getMessage()); } json_success('获取成功', $list); } public function getRightUsers( ){ // 获取登录用户信息 $userinfo = $this->getYysLoginUserinfo(); // 获取权限范围内的用户id $creator_ids = $this->getRightCreatorIds($userinfo); if ($creator_ids === false) { json_fail('获取失败'); } $cond = [ 'username' => ['NOT IN', 'admin,manage'] ]; if (is_array($creator_ids)) { $cond['id'] = ['IN', $creator_ids]; } if ($creator_ids === true) { $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']]; $devide_user_ids = M('roles')->where($where)->getField('id', true); $device_ids = join(',', $devide_user_ids); $list = M('users')->alias('u')->field('u.id,u.realname,u.phone') ->where($cond) ->distinct(true) ->join("INNER JOIN user_has_roles r ON u.id=r.uid AND r.role_id NOT IN ({$device_ids})") ->select() ?:[]; } else { $list = M('users')->field('id,realname,phone')->distinct(true)->where($cond)->select(); } json_success('获取成功', $list); } public function getUserAlarmRecords( ){ header('Access-Control-Allow-Origin: *'); $post_data = json_decode(file_get_contents('php://input'), true); $openid = $post_data['openid']; $userid = $post_data['userid']; //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $limit = isset($post_data['limit']) ? $post_data['limit'] : 10; $page = isset($post_data['page']) ? $post_data['page'] : 1; // 告警记录条件 $where = ['user_id' => $userid]; $device_numbers = M('devices')->where($where)->getField('imei', true); if (empty($device_numbers)) { json_fail('暂无设备,请先绑定设备'); } // 初始化条件 $cond = [ 'device_number' => ['IN', $device_numbers], ]; $reason = I('get.reason'); $state = I('get.state'); $result = I('get.result'); if ($reason) { if ($reason == 'fence') { $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out']]; } else { $cond['alarm_reason'] = $reason; } } else { // 默认只显示 SOS $cond['alarm_reason'] = 'press'; } if ($state) { $cond['state'] = $state; } if ($result !== '' && is_numeric($result)) { $cond['result'] = $result; } // 查出总数量 $list = []; $total = M('alarm_records')->where($cond)->count(); if ($total) { if ($state == 'start' || $state == 'end') { $order = "{$state}_time desc"; } else { $order = 'id desc'; } $fields = 'id,device_number,alarm_reason,handler_id,start_time,end_time,state,comment,result'; $list = M('alarm_records')->field($fields)->where($cond)->limit($limit)->page($page)->order($order)->select() ?: []; if (!empty($list)) { // alarm_reason,handler_id,result // 获取告警类型 $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id'); $reason_arr = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value'); // 处理结果 $result_arr = [ 0 => '待处理', 1 => '已处理', 2 => '误报', ]; // 中文转换 foreach ($list as &$alarm) { $alarm['start_time'] = $alarm['start_time'] ? date('Y-m-d H:i:s', $alarm['start_time']) : ''; $alarm['end_time'] = $alarm['end_time'] ? date('Y-m-d H:i:s', $alarm['end_time']) : ''; if (is_array($reason_arr)) { $alarm['alarm_reason'] = $reason_arr[$alarm['alarm_reason']]; } if (is_numeric($alarm['result'])) { $alarm['result'] = $result_arr[$alarm['result']]; } } } } // 返回 $data = [ 'total' => $total, 'limit' => $limit, 'page' => $page, 'list' => $list, ]; json_success('获取成功', $data); } public function getUserAlarmDetail( ){ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); if(!$userid || $userid == 'undefined' || $userid == 'null'){ json_fail('获取不到你的用户标识,请重新登陆'); } //检测登录状态 $res = $this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $alarm_id = I('get.id'); if (!$alarm_id) { json_fail('获取告警信息失败1'); } // 查出告警数据 $where = ['id' => $alarm_id]; $alarm_info = M('alarm_records')->where($where)->find(); if (empty($alarm_info)) { json_fail('获取告警信息失败2'); } $report_id = I('get.rid'); if (!$report_id) { json_fail('获取告警信息失败3'); } $where = ['id' => $report_id]; $alarm_report = M('alarm_report')->where($where)->find(); if (empty($alarm_report)) { json_fail('获取告警信息失败4'); } $alarm_info['address']=$alarm_report['address']; // 查出设备信息 $where = ['imei' => $alarm_info['device_number']]; $device_info = M('devices')->where($where)->find(); if (empty($alarm_info)) { json_fail('获取告警设备信息失败'); } if ($device_info['online_time'] > $device_info['wifi_online_time']) { $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']); $device_info['last_location'] = $device_info['longitude'] .','. $device_info['latitude']; $res = bmap_geocoding($device_info['latitude'], $device_info['longitude']); if($res['success']){ $device_info['address'] = $res['address']; }else{ $device_info['address']=''; } } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) { $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']); $device_info['last_location'] = $device_info['wifi_longitude'] .','. $device_info['wifi_latitude']; } else { $device_info['last_online_time'] = '0000-00-00 00:00:00'; $device_info['last_location'] = ''; $device_info['address']=''; } // 查出设备用户 if ($device_info['badge_user_id']) { $where = ['id' => $device_info['badge_user_id']]; $user_info = M('badgeuser')->where($where)->find() ?: []; } else { $where = ['id' => $device_info['user_id']]; $user_info = M('users')->where($where)->find() ?: []; } //if (empty($user_info)) { //json_fail('获取告警用户信息失败'); //} // 获取紧急联系人 $where = ['device_id' => $device_info['id']]; $urgent_list = M('kq_urgent')->where($where)->select() ? : []; if (!empty($urgent_list)) { $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id'); $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value'); foreach ($urgent_list as $key => &$urgent) { $urgent['relationship_text'] = $ships[$urgent['relationship']]; } } // 部门名称 $alarm_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name'); $alarm_info['user_info'] = $user_info; $alarm_info['urgent_list'] = $urgent_list; $alarm_info['device_info'] = $device_info; $alarm_info['device_info']['department_name'] = $alarm_info['department_name']; json_success('获取成功', $alarm_info); } public function setFenceAlarmInterval( ){ //user_has_students header('Access-Control-Allow-Origin: *'); $fenceId = I('get.fenceId'); $interval = intval(I('get.interval') ); if(!$fenceId){ json_fail('获取不到围栏标识,请刷新下'); } if(!$interval){ json_fail('获取不到时间间隔,请重设重试'); } if($interval < 1 || $interval > 720){ json_fail('推送间隔目前只支持720分钟以内'); } $saveData = [ 'sent_interval' => $interval ]; $saveData['sent_interval'] = $interval * 60; $res = M('fences')->where(['id' => $fenceId])->save($saveData); if($res === false){ json_fail('修改推送间隔失败'); } json_success('修改推送间隔成功'); } public function resetPwd( ){ header('Access-Control-Allow-Origin: *'); // 通过手机号和短信验证码注册 $data = json_decode( file_get_contents("php://input") ,true); // 用户类型:个人(personal)、团体(group) $userType = $data['userType']; // 设备类型:卡牌(card)、徽章(badge) $deviceType = $data['deviceType']; // 团体卡牌用户(group_card_user) 不可注册 // 个人用户(personal),团体徽章用户(group_badge_user) 可注册 if ($userType == 'personal') { // 个人用户 $identify = 'personal'; } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户 $identify = 'group_badge_user'; } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户 $identify = 'group_card_user'; } else { json_fail('未知用户类型'); } if(!$data['phone']){ json_fail('手机号码不能为空'); } if(!$data['smsCode']){ json_fail('短信验证码不能为空'); } if(! $data['password']){ json_fail('密码不能为空'); } if(! $data['confirmPassword']){ json_fail('确认密码不能为空'); } if ($data['password'] != $data['confirmPassword']) { json_fail('两次密码不一致'); } // 获取角色id $roleId = M('roles')->where(['identify' => $identify])->getField('id'); if (!$roleId) { json_fail('未知角色类型'); } // 判断角色、号码是否已注册 $userinfo = M('users')->alias('a')->field('a.id')->where(['username'=>$data['phone']])->join("INNER JOIN user_has_roles b ON a.id = b.uid AND b.role_id = {$roleId}")->find(); if (empty($userinfo)) { json_fail('该号码未注册'); } // 验证码有效性 $res = $this->isValidSmsCode($data['phone'], $data['smsCode']); if (!$res['success']) { json_fail($res['message']); } // 重置密码 $savePwd = password_hash($data['password'], PASSWORD_DEFAULT); $cond = ['id' => $userinfo['id']]; $res = M('users')->where($cond)->setField('password', $savePwd); if($res === false){ json_fail('重置失败'); } json_success('重置成功'); } public function checkSingleLogin( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); $openid = I('get.openid'); $where = [ 'id' => $userid, 'wx_open_id'=> $openid ]; $flag = M('users')->where($where)->find(); if($flag){ json_success('goon'); } json_fail('relogin'); } public function verify_vehicle_code( ){ header('Access-Control-Allow-Origin: *'); $postData = json_decode( file_get_contents('php://input'), true ); $licenseCode = $postData['licenseCode']; $plateCode = $postData['plateCode']; $rfidCode = $postData['rfidCode']; if(!$licenseCode){ json_fail('服务端未收到证件码'); } if(!$plateCode){ json_fail('服务端未收到车牌码'); } if($licenseCode !== $plateCode){ json_fail('服务端判断车牌码与证件码不一致'); } if(!$rfidCode){ json_fail('服务端未收到标签码'); } $addTime = time(); //java -classpath "/home/wwwroot/api.wxt.renlianiot.com/.data/java_qr" TendencyEncrypt [code] $prefix = 'java -classpath "/home/wwwroot/api.wxt.renlianiot.com/java_qr" TendencyEncrypt '; $cmd = $prefix . $licenseCode; $decodeRes = exec($cmd); if(strlen($decodeRes) !== 7 ){ $errContent = '['. date('Y-m-d H:i:s') . ']' . ' decode qrcode failed, QRCONTENT:'. $licenseCode . '| RFID:'.$rfidCode.PHP_EOL; debug_log('license_decode_error', $errContent); json_fail('二维码内容解码失败,请检查'); } $saveData = [ 'license_code' => $licenseCode, 'rfid_code' => $rfidCode, 'created_at' => $addTime, 'decode_result' => $decodeRes ]; $res = M('vehice_code_verify')->add($saveData); if($res === false){ json_fail('添加失败,数据库异常或重复添加'); } $count = M('vehice_code_verify')->count(); json_success('success', $count); } public function getSeriCount( ){ header('Access-Control-Allow-Origin: *'); $count = M('vehice_code_verify')->count(); if($count ===false){ json_fail('服务端异常'); } json_success('success', $count); } public function decodeContent( ){ header('Access-Control-Allow-Origin: *'); $list = M('vehice_code_verify')->select(); $prefix = 'java -classpath "/home/wwwroot/api.wxt.renlianiot.com/java_qr" TendencyEncrypt '; foreach($list as $v){ $cmd = $prefix . $v['license_code']; $decodeRes = exec($cmd); if(strlen($decodeRes) !== 7 ){ $errContent = '['. date('Y-m-d H:i:s') . ']' . ' decode qrcode failed, QRCONTENT:'. $v['license_code'] . '| RFID:'.$v['rfid_code'].PHP_EOL; debug_log('license_decode_error', $errContent); continue; } $res = M('vehice_code_verify')->where(['id' => $v['id']])->save(['decode_result' => $decodeRes]); } } public function exportSql_km( ){ $start = intval(I('get.start')); $end = intval(I('get.end')); if(!$start || !$end){ json_fail('缺少参数,起止参数都需要'); } $where= [ 'id' => [ ['EGT', $start], ['ELT', $end]], ]; $list = M('vehice_code_verify')->where($where)->select(); $prefix = "INSERT INTO TB_ELECTRICCARS_CODE (PLATENUMBER,THEFTNO,THEFTNO2,ICNO,ORI_THEFTNO,ORI_THEFTNO2)VALUES('"; $fileName = SOLUTION_LOG_PATH .'km_sql_export/sql_after_transform'.time().'.sql'; $folder=dirname($fileName); if (!is_dir($folder)){ mkdir($folder,0777,true); } $param4 = 'null'; foreach($list as $v){ $param1 = $v['decode_result']; //param1 $hex = dechex($v['rfid_code']); $hexRes = str_pad($hex, 8,'0' , STR_PAD_LEFT); $param5 = '8023'.$v['rfid_code']; $param6 = '8021'.$v['rfid_code']; $param2 = hexdec('8023'.$hexRes); $param3 = hexdec('8021'.$hexRes); $sqlStr = $prefix . $param1 . "'," . $param2 . ',' . $param3 . ',' . $param4 . ',' . $param5 . ',' . $param6 . ');' . PHP_EOL; file_put_contents($fileName,$sqlStr ,FILE_APPEND); } echo 'export file path: '. $fileName; } public function decodeQrSecret( ){ header('Access-Control-Allow-Origin: *'); $postData = json_decode( file_get_contents('php://input'), true); $code = $postData['qrCode']; $type = $postData['type']; $prefix = 'java -classpath "/home/wwwroot/api.wxt.renlianiot.com/java_qr" TendencyEncrypt '; $cmd = $prefix . $code; $decodeRes = exec($cmd); if(strlen($decodeRes) !== 7 ){ $errContent = '['. date('Y-m-d H:i:s') . ']' . ' decode 【'.$type.' 】qrcode failed, QRCONTENT:'. $code. 'JAVA_RESP:'.$decodeRes .PHP_EOL; debug_log('license_decode_error', $errContent); json_fail('解码失败'); } json_success('decode success',$decodeRes); } private function getMaxDbm( $avFile, $start ){ /* $string = file_get_contents($avFile); $bytes = array(); for($i = 0; $i < strlen($string); $i++){ $bytes[] = ord($string[$i]); } $counter = strlen($string); */ $counter = 4; $bytes = [1,2,3,4]; $absolute = 0; $maximum = 0; for ($i = $start; $i < $counter; $i++) { // $absolute = abs(getShort(new byte[] {vector[i], vector[i + 1]}, 0)); $absolute = abs( $this->bytesToShort([$bytes[$i], $bytes[$i+1]], 0) ) ; if ($absolute > $maximum) { $maximum = $absolute; } $i++; } if ($maximum > 32767) { $maximum = 32767; } return (int)$maximum; } public function test_cus_function( ){ $avFile = '/data/wwwroot/wxt.rltest.cn/1.0.0/.data/rec-869678040083761-1638237389747.wav'; $res = $this->getMaxDbm($avFile, 44); var_dump($res);exit; } private function bytesToShort( $bytes, $position ){ $val = 0; $val = $bytes[$position + 1] & 0xFF; $val = $val << 8; $val |= $bytes[$position] & 0xFF; return $val; } public function getDeviceAvatar( ){ header('Access-Control-Allow-Origin: *'); $imei = I('get.imei'); if(!$imei){ json_fail('获取不到设备标识'); } $avatar = M('devices')->where(['imei' => $imei])->getField('avatar'); if(!$avatar){ json_fail('获取头像失败'); } json_success('获取头像成功',$avatar); } public function getUserAvatar( ){ header('Access-Control-Allow-Origin: *'); $uid = I('get.uid'); if(!$uid){ json_fail('获取不到用户标识'); } $avatar = M('users')->where(['id' => $uid])->getField('avatar'); if(!$avatar){ json_fail('获取头像失败'); } json_success('获取头像成功',$avatar); } public function saveDeviceAvatar( ){ header('Access-Control-Allow-Origin: *'); $postData = json_decode( file_get_contents('php://input'), true); if(!$postData['imei']){ json_fail('获取不到设备标识'); } if(!$postData['avatar64content']){ json_fail('获取不到头像信息'); } $folder = realpath(__ROOT__).'/static/assets/avatar/'.date('Ymd').'/'; if (!is_dir($folder)){ $mres= mkdir($folder,0777,true); if($mres === false){ json_fail('服务端创建目录权限不足'); } } $fileName = 'avatar-device-imei'.$postData['imei'] .'-'. time(); $saveFile = $this->base64_image_content($postData['avatar64content'], $folder, $fileName); if(!$saveFile){ json_fail('服务端保存头像失败'); } $res = M('devices')->where(['imei' => $postData['imei']])->save(['avatar' => $saveFile]); if($res === false){ json_fail('保存头像地址失败'); } json_success('保存成功'); } public function saveUserAvatar( ){ header('Access-Control-Allow-Origin: *'); $postData = json_decode( file_get_contents('php://input'), true); if(!$postData['uid']){ json_fail('获取不到用户标识'); } if(!$postData['avatar64content']){ json_fail('获取不到头像信息'); } $folder = realpath(__ROOT__).'/static/assets/avatar/'.date('Ymd').'/'; if (!is_dir($folder)){ $mres= mkdir($folder,0777,true); if($mres === false){ json_fail('服务端创建目录权限不足'); } } $fileName = 'avatar-user-uid'.$postData['uid'] .'-'. time(); $saveFile = $this->base64_image_content($postData['avatar64content'], $folder, $fileName); if(!$saveFile){ json_fail('服务端保存头像失败'); } $res = M('users')->where(['id' => $postData['uid']])->save(['avatar' => $saveFile]); if($res === false){ json_fail('保存头像地址失败'); } json_success('保存成功'); } private function base64_image_content( $base64_image_content, $path, $name ){ //匹配出图片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = $path.$name.".{$type}"; $file = 'http://'.$_SERVER['HTTP_HOST'].'/static/assets/avatar/'.date('Ymd').'/'.$name.".{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ return $file; }else{ return false; } }else{ return false; } } public function setLocModel( ){ /* 请求url上带上 openid userid post请求 参数: imei id(设备id) post_mode 定位模式 0-常规模式 1-追踪模式 2-定时模式 定时模式:需要设置 定位采样间隔(stopped_rtc_invl) 定位上报间隔(stopped_rpt_invl) */ header('Access-Control-Allow-Origin: *'); $openid = I('get.openid'); $userid = I('get.userid'); //检测登录状态 $res=$this->checkLoginState($openid,$userid); if(!$res['status']){ json_fail($res['message']); } $data = json_decode( file_get_contents("php://input") ,true); $imei=$data['imei']; if(!$imei){ json_fail('缺少设备imei号'); } $config['pos_mode']=$data['pos_mode']; if(!isset($config['pos_mode']) || $config['pos_mode'] === ''){ json_fail('缺少定位模式'); } $dev_id=$data['id']; if(!$dev_id){ json_fail('缺少设备id'); } $redis = Redis('c61_gps_device_configs_'.$imei,"queue"); //开启事务 M()->startTrans(); $config['msg_id'] = 0xAAAA0010; //判断是不是定时模式 if ($config['pos_mode'] == 2) { if(!$data['stopped_rtc_invl']){ json_fail('请设置定位采样间隔'); } if(!$data['stopped_rpt_invl']){ json_fail('请设置定位上报间隔'); } $config_arr = array( 'stopped_rtc_invl' => intval($data['stopped_rtc_invl']), 'stopped_rpt_invl' => intval($data['stopped_rpt_invl']), 'msg_id' => 0xAAAA0007 ); //下发日志 $log_data = array( 'send_contents' => json_encode($config_arr), 'type'=>'sensor', 'imei'=>$imei, 'created_at' => time(), 'creator_id' => $userid, 'device_id' => $dev_id ); $lg_id = M('send_config_log')->createAdd($log_data); if (!$lg_id) { json_fail('下发日志添加失败'); M()->rollback(); } $config_arr['id'] = $lg_id; $redis->push(json_encode($config_arr)); }else{//非定时模式 采样时间设为3000 上报间隔3600 $config_arr = array( 'stopped_rtc_invl' => 3000, 'stopped_rpt_invl' => 3600, 'msg_id' => 0xAAAA0007 ); //下发日志 $log_data = array( 'send_contents' => json_encode($config_arr), 'type'=>'sensor', 'imei'=>$imei, 'created_at' => time(), 'creator_id' => $userid, 'device_id' => $dev_id ); $lg_id = M('send_config_log')->createAdd($log_data); if (!$lg_id) { json_fail('下发日志添加失败'); M()->rollback(); } $config_arr['id'] = $lg_id; $redis->push(json_encode($config_arr)); } //下发日志 $log_data = array( 'send_contents' => json_encode($config), 'type'=>'pos_mode', 'imei'=>$imei, 'created_at' => time(), 'creator_id' => $userid, 'device_id' => $dev_id ); $config['id'] = M('send_config_log')->createAdd($log_data); if (!$config['id']) { json_fail('下发日志添加失败'); M()->rollback(); } $redis->push(json_encode($config)); M()->commit(); json_success('设置成功'); } public function addToVoiceCenter( $imei ){ $code=C('VOICE_CENTER_CODE'); if(!$code){ return array('success'=>false,'message'=>'VOICE_CENTER_CODE not set'); } $url =C('VOICE_CENTER_URL')?C('VOICE_CENTER_URL'):'http://47.114.185.186:8103/?s=voicecenter/deviceAddToCenter'; $post_data=array( 'imei'=>$imei, 'code'=>$code, ); $send_res = curl_http_post(http_build_query($post_data),$url,false); $result=json_decode($send_res,true); if($result['success']){ //修改设备同步状态 $res=M('devices')->createSave(array('imei'=>$imei),['sync_status' => 1]); return array('success'=>true,'message'=>'同步成功'); }else{ return array('success'=>false,'message'=>'同步失败'); } } public function delUserFence( ){ header('Access-Control-Allow-Origin: *'); $userid = I('get.userid'); if(!$userid){ json_fail('获取不到用户标识,尝试重登'); } $fenceId =I('get.fenceId'); if(!$fenceId){ json_fail('获取不到围栏标识,尝试刷新'); } $res = M('fences')->where(['id' => $fenceId, 'creator_id' => $userid, 'fence_type' => 1] )->delete(); if(!$res){ json_fail('删除失败'); } json_success('删除成功'); } public function sendReverveNotice( ){ header('Access-Control-Allow-Origin: *'); $voice_template_id=C('WX_VOICE_TEMPLATE_ID'); if(!$voice_template_id){ debug_log('voice_notice','WX_VOICE_TEMPLATE_ID not exist'); return false; } $data=$_POST; $this->wxMsg = new \Jiaruan\WxTmp(); $access_token =$this->wxMsg->getAccessToken(); $msgArray= array( "touser"=>$data['openid'], "msgtype"=>"text", "text"=>array( "content"=>urlencode("测试啥是") ) ); $json=urldecode(json_encode($msgArray)); //var_dump($json);exit; #群发 文本消息 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $res = json_decode(curl_exec($ch),true); curl_close($ch); json_success($res); } }