$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); $identify = 'chezhu'; $role_id = M('roles')->where(array('identify'=>$identify))->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('密码错误'); } $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 $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('未检测到用户标识'); } $vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true); $devices=M('devices')->where(['bind_id' =>array('in',$vehiclesIds) ])->select(); if(!$devices){ json_fail('名下查询不到任何设备'); } $resp = []; foreach($devices as &$locationInfo){ //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']; $locationInfo['address'] = $locationInfo['address']; if(!$locationInfo['time']){ $locationInfo['awayTime'] = '从未在线'; }else{ $timeInterval = time() - (int)strtotime($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'] =$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']); } //$vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true); //$devices=M('devices')->where(['bind_id' =>array('in',$vehiclesIds) ])->select(); $list=M('vehicles')->where(array('user_id'=>$userid,'deleted_at'=>0))->select(); $type_id=M('sys_dict_type')->where(['code'=>'DeviceType'])->getField('id'); foreach($list as &$val){ $device_info=M('devices')->where(['bind_id' =>$val['id']])->find(); if(!$device_info){ $device_info=[ 'name'=>'-', 'imei'=>'-', 'loc_mode'=>'-', ]; } $val['device_info']=$device_info; $val['department_name']=M('departments')->where(['id'=>$val['department_id']])->getField('department_name'); $val['creator']=M('users')->where(['id'=>$val['creator_id']])->getField('username'); } if(!$list){ json_fail('暂无车辆'); } json_success('查询成功',$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 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(); $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_unshift($arr, $v); } } $routeInfo =$arr; //$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 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 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 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('查询不到该设备当前信息哦!'); } //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']; $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(); $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 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); } 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); } 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'); } 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( ){ $accessKeyId='LTAIOSQ4y09Jxbf3'; $accessKeySecret='LQm05sOLBss87lFG6jx9iq4lzKCAqA'; $config = new \Darabonba\OpenApi\Models\Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret ]); // 访问的域名 $config->endpoint = "dysmsapi.aliyuncs.com"; $client= new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config); $params = [ "signName" => "小友回收", "templateCode" => "SMS_245515027", "phoneNumbers" => 15706857065, "templateParam" => json_encode(['code' => '1234']) ]; // $client = self::createClient( $accessKeyId, $accessKeySecret); $sendSmsRequest = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest($params); $runtime = new \AlibabaCloud\Tea\Utils\Utils\RuntimeOptions([]); $res=$client->sendSmsWithOptions($sendSmsRequest, $runtime); var_dump($res); } 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 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); } public function getMyInsureList( ){ 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']); } $vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true); $list=M('insure_records')->where(['vehicle_id' =>array('in',$vehiclesIds) ])->select(); foreach($list as &$val){ $start_at=strtotime(date('Y-m-d 00:00:00',$val['start_at'])); $end_at=strtotime(date('Y-m-d 23:59:59',$val['end_at'])); if(time()<$start_at){ $val['insure_state']=0; $val['insure_state_text']='待生效'; }elseif(time()<=$end_at){ $val['insure_state']=1; $val['insure_state_text']='生效中'; }else{ $val['insure_state']=2; $val['insure_state_text']='已失效'; } $val['vehicle_info']=M('vehicles')->where(['id' =>$val['vehicle_id']])->find(); $val['insure_info']=M('insurance')->where(['id' =>$val['insurance_id']])->find(); $val['start_at']=date('Y-m-d 00:00:00',$val['start_at']); $val['end_at']=date('Y-m-d 23:59:59',$val['end_at']); } if(!$list){ json_fail('暂无保险'); } json_success('查询成功',$list); } public function getInsureOptions( ){ header('Access-Control-Allow-Origin: *'); $list=M('insurance')->where(['enable' =>1])->field('*,name as text,id as value')->select(); foreach($list as &$val){ $val['price']=$val['price']*100; } json_success('查询成功',$list); } public function userByInsure( ){ 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); $insurance_data=M('insurance')->where(['id'=>$data['insure_id']])->find(); //添加保险记录信息 $insurance = array( 'vehicle_id'=>$data['vehicle_id'], 'insurance_id'=>$data['insure_id'], 'start_at'=>strtotime(date('Y-m-d',strtotime('+1 day'))), 'end_at'=>strtotime(date('Y-m-d',strtotime('+'.$insurance_data['years'].' year')))+24*3600-1, 'creator_id'=>$userid, 'created_at'=>time(), 'updated_at'=>time() ); if(!M('insure_records')->createAdd($insurance)){ json_fail('添加保险失败'); } json_success('购买成功',$userid); } }