WxApiAction.class.php 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507
  1. <?php
  2. class WxApiAction extends Action {
  3. private function getHumenTime( $timeInterval ){
  4. if ($timeInterval < 60){
  5. $formatime = $timeInterval.'秒';
  6. }elseif($timeInterval < 60 * 60){
  7. $min = floor($timeInterval/60);
  8. $formatime = $min.'分钟';
  9. }elseif($timeInterval < 60 * 60 * 24){
  10. $h = floor($timeInterval/(60*60));
  11. $formatime = $h.'小时';
  12. }elseif($timeInterval < 60 * 60 * 24 * 30){
  13. $d = floor($timeInterval/(60*60*24));
  14. $formatime = $d.'天';
  15. }elseif($timeInterval < 60 * 60 * 24 * 30 * 12){
  16. $m = floor($timeInterval/(60*60*24*30));
  17. $formatime = $m.'月';
  18. }else{
  19. $y = floor($timeInterval/(60*60*24*30*12));
  20. $formatime = $y.'年';
  21. }
  22. return $formatime;
  23. }
  24. public function register( ){
  25. header('Access-Control-Allow-Origin: *');
  26. // 通过手机号和短信验证码注册
  27. $data = json_decode( file_get_contents("php://input") ,true);
  28. // 用户类型:个人(personal)、团体(group)
  29. $userType = $data['userType'];
  30. // 设备类型:卡牌(card)、徽章(badge)
  31. $deviceType = $data['deviceType'];
  32. // 团体卡牌用户(group_card_user) 不可注册
  33. // 个人用户(personal),团体徽章用户(group_badge_user) 可注册
  34. if ($userType == 'personal') { // 个人用户
  35. $identify = 'personal';
  36. } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户
  37. $identify = 'group_badge_user';
  38. } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户
  39. // $identify = 'group_card_user';
  40. json_fail('团体卡牌用户无需注册,请联系发卡人询问账号!');
  41. } else {
  42. json_fail('未知用户类型');
  43. }
  44. if(!$data['phone']){
  45. json_fail('手机号码不能为空');
  46. }
  47. if(!$data['smsCode']){
  48. json_fail('短信验证码不能为空');
  49. }
  50. if(! $data['password']){
  51. json_fail('密码不能为空');
  52. }
  53. if(! $data['confirmPassword']){
  54. json_fail('请输入确认密码');
  55. }
  56. if ($data['password'] != $data['confirmPassword']) {
  57. json_fail('两次密码不一致');
  58. }
  59. /*
  60. $cond = array(
  61. 'username'=>$data['phone']
  62. );
  63. $user_info = M('users')->where($cond)->join('user_has_roles ON users.id = user_has_roles.uid')->find();
  64. if($user_info){
  65. //存在用户则判断
  66. $role_identify=M('roles')->where(array('id'=>$user_info['role_id']))->getField('identify');
  67. if($role_identify==$identify){
  68. json_fail('该类型用户已经存在,请前往登陆');
  69. }
  70. }*/
  71. // 获取角色id
  72. $roleId = M('roles')->where(['identify' => $identify])->getField('id');
  73. if (!$roleId) {
  74. json_fail('未知角色类型');
  75. }
  76. // 判断角色、号码是否已注册
  77. $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();
  78. if ($userinfo) {
  79. json_fail('该号码已注册');
  80. }
  81. // 验证码有效性
  82. $res = $this->isValidSmsCode($data['phone'], $data['smsCode']);
  83. if (!$res['success']) {
  84. json_fail($res['message']);
  85. }
  86. //if($user_info['password'] != password_hash($data['password'],PASSWORD_DEFAULT) ){
  87. $savePwd = password_hash($data['password'],PASSWORD_DEFAULT);
  88. $saveData = [
  89. 'username' => $data['phone'],
  90. 'realname' => '用户'.$data['phone'],
  91. 'password' => $savePwd,
  92. 'phone' => $data['phone'],
  93. 'created_at' => time(),
  94. ];
  95. // 个人用户给定默认部门
  96. if ($identify == 'personal') {
  97. $where = [
  98. 'type' => 'basic_config',
  99. 'field' => 'department_id',
  100. ];
  101. $department_id = M('sys_config')->where($where)->getField('fieldValue');
  102. if ($department_id) {
  103. $saveData['department_id'] = $department_id;
  104. }
  105. }
  106. M()->startTrans();
  107. $userid = M('users')->add($saveData);
  108. if(!$userid){
  109. M()->rollback();
  110. json_fail('注册失败');
  111. }
  112. $hasRoleData = [
  113. 'uid' => $userid,
  114. 'role_id' => $roleId
  115. ];
  116. $userHasRoleRes = M('user_has_roles')->add($hasRoleData);
  117. if(!$userHasRoleRes){
  118. M()->rollback();
  119. json_fail('注册失败');
  120. }
  121. M()->commit();
  122. json_success('注册成功',$userid);
  123. }
  124. public function login( ){
  125. header('Access-Control-Allow-Origin: *');
  126. //json_fail('登录失败');
  127. $openid = I('get.openid');
  128. if(!$openid){
  129. json_fail('未授权,请关闭当前页面重新进入');
  130. }
  131. $data = json_decode( file_get_contents("php://input") ,true);
  132. $identify = 'chezhu';
  133. $role_id = M('roles')->where(array('identify'=>$identify))->getField('id');
  134. if (!$role_id) {
  135. json_fail('未知用户类型');
  136. }
  137. $cond = array(
  138. 'username' => $data['username'],
  139. );
  140. $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();
  141. if(!$user_info){
  142. json_fail('账号错误');
  143. }
  144. if(!password_verify($data['password'], $user_info['password'])){
  145. json_fail('密码错误');
  146. }
  147. $where = array(
  148. 'wx_open_id' => $openid,
  149. 'id' => ['NEQ', $user_info['uid']],
  150. );
  151. //$result = M('users')->createSave($where,['wx_open_id'=>'']);
  152. $result = M('users')->where($where)->save(['wx_open_id'=>'']);
  153. if($result===false){
  154. json_fail('登陆失败');
  155. }
  156. if($user_info['wx_open_id'] != $openid){
  157. $update = array(
  158. 'wx_open_id' => $openid,
  159. 'last_login_ip' => $_SERVER['REMOTE_ADDR'],
  160. 'last_login_time' => time(),
  161. );
  162. $result = M('users')->createSave(array('id'=>$user_info['uid']),$update);
  163. if(!$result){
  164. json_fail('登陆失败');
  165. }
  166. }
  167. //如果当前openid与其他账号openid相同,清空其他表中openid
  168. $res = array(
  169. 'id'=>$user_info['uid'],
  170. 'realname'=>$user_info['realname'],
  171. 'avatar' => $user_info['avatar'],
  172. 'phone'=>$user_info['phone'],
  173. );
  174. json_success('登录成功', $res);
  175. }
  176. public function getLastPositionMulti( ){
  177. header('Access-Control-Allow-Origin: *');
  178. $userid = I('get.userid');
  179. if(!$userid){
  180. json_fail('未检测到用户标识');
  181. }
  182. $vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true);
  183. $devices=M('devices')->where(['bind_id' =>array('in',$vehiclesIds) ])->select();
  184. if(!$devices){
  185. json_fail('名下查询不到任何设备');
  186. }
  187. $resp = [];
  188. foreach($devices as &$locationInfo){
  189. //wifi_online_time
  190. //wifi_longitude
  191. //wifi_latitude
  192. //addr
  193. $locationInfo['isAlarm'] = $locationInfo['alarm_status'];
  194. $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ;
  195. $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time'];
  196. $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude'];
  197. $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude'];
  198. $locationInfo['address'] = $locationInfo['address'];
  199. if(!$locationInfo['time']){
  200. $locationInfo['awayTime'] = '从未在线';
  201. }else{
  202. $timeInterval = time() - (int)$locationInfo['time'];
  203. $locationInfo['awayTime'] = $this->getHumenTime($timeInterval);
  204. }
  205. $lngLatAlter = new \Jms\Algo\Geometry();
  206. if(!$locationInfo['lat'] || !$locationInfo['lng']){
  207. continue;
  208. }
  209. $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']);
  210. $locationInfo['lat'] = $latLng['lat'];
  211. $locationInfo['lng'] = $latLng['lng'];
  212. $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']);
  213. array_push($resp, $locationInfo);
  214. }
  215. if(!$resp){
  216. json_fail('暂无任何设备上报过数据哦!');
  217. }
  218. json_success('查询成功', $resp);
  219. }
  220. private function checkLoginState( $openid, $userid ){
  221. $wx_open_id=M('users')->where(array('id'=>$userid))->getField('wx_open_id');
  222. if($wx_open_id === 'test_openid'){
  223. return array('status'=>true,'message'=>'');
  224. }
  225. if($wx_open_id!=$openid){
  226. //已被他人登录
  227. return array('status'=>false,'message'=>'账号可能在其他设备登录,请重新登录');
  228. }
  229. return array('status'=>true,'message'=>'');
  230. }
  231. public function getMyDevices( ){
  232. header('Access-Control-Allow-Origin: *');
  233. $openid = I('get.openid');
  234. $userid = I('get.userid');
  235. //检测登录状态
  236. $res=$this->checkLoginState($openid,$userid);
  237. if(!$res['status']){
  238. json_fail($res['message']);
  239. }
  240. //$vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true);
  241. //$devices=M('devices')->where(['bind_id' =>array('in',$vehiclesIds) ])->select();
  242. $list=M('vehicles')->where(array('user_id'=>$userid))->select();
  243. $type_id=M('sys_dict_type')->where(['code'=>'DeviceType'])->getField('id');
  244. foreach($list as &$val){
  245. $val['device_info']=M('devices')->where(['bind_id' =>$val['id']])->find();
  246. $val['department_name']=M('departments')->where(['id'=>$val['department_id']])->getField('department_name');
  247. $val['creator']=M('users')->where(['id'=>$val['creator_id']])->getField('username');
  248. }
  249. if(!$list){
  250. json_fail('暂无车辆');
  251. }
  252. json_success('查询成功',$list);
  253. }
  254. public function getAlarmList( ){
  255. header('Access-Control-Allow-Origin: *');
  256. $userid = I('get.userid');
  257. if(!$userid || $userid == 'undefined' || $userid == 'null'){
  258. json_fail('获取不到你的用户标识,请重新登陆');
  259. }
  260. $openid = I('get.openid');
  261. //检测登录状态
  262. $res=$this->checkLoginState($openid,$userid);
  263. if(!$res['status']){
  264. json_fail($res['message']);
  265. }
  266. $imeiArr=M('devices')->where(['user_id' => $userid])->getField('imei',true);
  267. $page = I('get.page') ? I('get.page') : 1;
  268. $pageSize = 10;
  269. $start = ($page - 1) * $pageSize;
  270. $cond = [];
  271. $alarmType = I('get.alarmType');
  272. $imei = I('get.imei');
  273. if(!$imei){
  274. $cond['device_number'] = array('in',$imeiArr);
  275. }else{
  276. $cond['device_number'] = $imei;
  277. }
  278. if($alarmType){
  279. $cond['alarm_type'] = $alarmType;
  280. }
  281. $list = M('alarm_report')->where($cond)->limit( $start, $pageSize)->order('created_at desc')->select();
  282. $type_id=M('sys_dict_type')->where(array('code'=>'AlarmType'))->getField('id');
  283. foreach($list as &$val){
  284. $val['alarm_type_str']=M('sys_dict_data')->where(array('type_id'=>$type_id,'code'=>$val['alarm_type']))->getField('value');
  285. $val['created_at_str'] = date('Y-m-d H:i:s', $val['created_at']);
  286. }
  287. $total = M('alarm_report')->where($cond)->count() ?: 0;
  288. $resp = [
  289. 'list' => $list ?:[],
  290. 'total' => $total,
  291. 'pageSize' => $pageSize
  292. ];
  293. json_success('获取成功', $resp);
  294. }
  295. public function getSignaturEtc( ){
  296. header('Access-Control-Allow-Origin: *');
  297. $url = I('get.url');
  298. if(!$url){
  299. json_fail('no url');
  300. }
  301. $url = urldecode($url);
  302. $accessToken = $this->getWeixinAccessToken();
  303. if (!$accessToken) {
  304. json_fail('获取 access token 失败');
  305. }
  306. $apiTiket = $this->getJsapiTikcet($accessToken);
  307. if(is_array($apiTiket)){
  308. json_fail($apiTiket['errcode'].':'.$apiTiket['errmsg']);
  309. }
  310. $noncestr = substr(md5(time()), 0, 16);
  311. $timestamp = time();
  312. //jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value
  313. $str = 'jsapi_ticket='.$apiTiket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
  314. $signature = sha1($str);
  315. $data = [
  316. 'appId' => C('WECHAT_APPID'),
  317. 'timeStamp' => $timestamp,
  318. 'nonceStr' => $noncestr,
  319. 'signature' => $signature,
  320. 'url' => $url,
  321. 'jsapi_ticket' =>S('wx_jsapi_ticket'),
  322. 'accessToken' => $accessToken,
  323. ];
  324. json_success('get success', $data);
  325. }
  326. private function getJsapiTikcet( $accessToken ){
  327. $jsapiTicket = S('wx_jsapi_ticket');
  328. if(!$jsapiTicket){
  329. $ch = curl_init();
  330. curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$accessToken .'&type=jsapi');
  331. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  332. $output = json_decode(curl_exec($ch), true);
  333. curl_close($ch);
  334. if($output['errcode'] != 0){
  335. return $output;
  336. }
  337. S('wx_jsapi_ticket', $output['ticket'], '7100');
  338. return $output['ticket'];
  339. }else{
  340. return $jsapiTicket;
  341. }
  342. }
  343. public function getGpsRoutes( ){
  344. header('Access-Control-Allow-Origin: *');
  345. $imei = I('get.imei');
  346. $startTime = I('get.startTime');
  347. $endTime = I('get.endTime');
  348. if(!$imei){
  349. json_fail('获取不到设备号');
  350. }
  351. if(!$startTime){
  352. json_fail('无起始时间');
  353. }
  354. if(!$endTime){
  355. json_fail('无结束时间');
  356. }
  357. //end_time
  358. //start_time
  359. //student_id
  360. //queyRouteListByStudentId
  361. $routeInfo = [];
  362. $lngLatAlter = new \Jms\Algo\Geometry();
  363. $routeInfo = queyGpsRouteListByimei($imei, $startTime, $endTime);
  364. //$routeInfo = analyzeRouteInfoGaodeBatch($routeInfo);
  365. $routeInfo = analyzeRouteInfoWayzBatch($routeInfo);
  366. $arr = [];
  367. foreach($routeInfo as &$v){
  368. $v['lat'] = $v['Latitude'];
  369. $v['lng'] = $v['Longitude'];
  370. if($v['lat']){
  371. array_push($arr, $v);
  372. }
  373. }
  374. $routeInfo =$arr;
  375. //$routeInfo =bmapFilterOutliers($arr);
  376. }
  377. json_success('success', $routeInfo);
  378. }
  379. private function analyzeRouteInfo( $list ){
  380. if(!$list){
  381. return array();
  382. }
  383. $arr= [];
  384. foreach($list as $k=> $v){
  385. if(isset($v['WifiMacs']) && $v['WifiMacs'] !=''){
  386. $wifiRes =$this->requestWifiLBS($v);
  387. if($wifiRes['success']){
  388. if($wifiRes['data']['lon'] == '' || is_null($wifiRes['data']['lat'])){
  389. continue;
  390. }
  391. $list[$k]['Latitude'] = $wifiRes['data']['lat'];
  392. $list[$k]['Longitude'] = $wifiRes['data']['lon'];
  393. $list[$k]['SignalType'] = 'WiFi';
  394. $list[$k]['WifiAddress'] = $wifiRes['data']['address'];
  395. array_push($arr, $list[$k]);
  396. }else{
  397. // array_splice($list,$k,1);
  398. continue;
  399. }
  400. }else{
  401. $list[$k]['SignalType'] = 'GPS';
  402. array_push($arr, $list[$k]);
  403. }
  404. }
  405. return $arr;
  406. }
  407. private function requestWifiLBS( $routeInfo ){
  408. if(!$routeInfo){
  409. return array(
  410. 'success' => false,
  411. 'msg' => '空数据'
  412. );
  413. }
  414. if(!isset( $routeInfo['WifiMacs']) ){
  415. return array(
  416. 'success' => false,
  417. 'msg' => '无wifi信息'
  418. );
  419. }
  420. $WifiMacs = $routeInfo['WifiMacs'];
  421. $userKey = '';
  422. if(!$userKey){
  423. $userKey = 'f107b0b3a513e6e37c6fb0424bed6633';
  424. }
  425. //$url = 'http://api.cellocation.com:81/loc/?wl=' . $WifiMacs .'&output=json&coord=gcj02';
  426. $url = 'http://apilocate.amap.com/position?accesstype=1&imei=' . $routeInfo['DeviceNumber'] . '&macs=' . $WifiMacs . '&key=' . $userKey;
  427. $curl = curl_init($url);
  428. curl_setopt($curl, CURLOPT_TIMEOUT, 3);
  429. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  430. $response = curl_exec($curl);
  431. if (curl_errno($curl)) {
  432. $errmsg = curl_error($curl);
  433. curl_close($curl);
  434. return array(
  435. 'success' => false,
  436. 'msg' => $errmsg
  437. );
  438. }
  439. curl_close($curl);
  440. $response = json_decode($response, true);
  441. if($response['info'] != 'OK' || count($response['result']) <2 ){
  442. return array(
  443. 'success' => false,
  444. 'msg' => $response['info']
  445. );
  446. }
  447. $result = $response['result'];
  448. $location = $response['result']['location'];
  449. $location = explode(',', $location);
  450. $response = array(
  451. 'lon' => $location[0],
  452. 'lat' => $location[1],
  453. 'address' => $result['desc']
  454. );
  455. return array(
  456. 'success' => true,
  457. 'data' => $response
  458. );
  459. }
  460. private function registerDevice2third( $deviceImei ){
  461. $tokenInfo = $this->getThirdTokenInfo();
  462. if(!$tokenInfo){
  463. return false;
  464. }
  465. $postData = [
  466. "deviceImei" => $deviceImei,
  467. "phone" => "",
  468. "userId" => $tokenInfo['holder']
  469. ];
  470. var_dump($postData);
  471. $url = "http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/device";
  472. $headers[] = "Content-Type: application/json";
  473. $headers[] = "Authorization: ". $tokenInfo['token'];
  474. $ch = curl_init();
  475. curl_setopt($ch, CURLOPT_URL, $url);
  476. curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
  477. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  478. curl_setopt($ch, CURLOPT_POST, 1);
  479. curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($postData) );
  480. $output = curl_exec($ch);
  481. curl_close($ch);
  482. if($output === false){
  483. $this->push_log('thirdapi_register_device_curl_error',curl_error($curl));
  484. return false;
  485. }
  486. $deviceRes = json_decode($output, ture) ;
  487. if($deviceRes['error'] || $deviceRes['code']){
  488. $this->push_log('thirdapi_register_device_response_error',$deviceRes);
  489. return false;
  490. }
  491. $this->push_log('thirdapi_register_device_response_success',$deviceRes);
  492. return true;
  493. }
  494. private function getThirdRoutes( $imei, $option ){
  495. /*
  496. {
  497. "page": 0,
  498. "size": 6000,
  499. "total": 8,
  500. "content": [{
  501. "collectDt": "2021-07-07 10:33:39",
  502. "receiveAt": "2021-07-07 10:33:39",
  503. "lat": "40.02577751048506",
  504. "lon": "116.35762812669113",
  505. "battery": 91,
  506. "positionType": 2,
  507. "imei": "71041607133",
  508. "isOnline": null
  509. }]
  510. }
  511. */
  512. if (!$imei) {
  513. $this->push_log('thirdapi_devicelocation_curl_error', 'imei 为空');
  514. return false;
  515. }
  516. $tokenInfo = $this->getThirdTokenInfo();
  517. if(!$tokenInfo){
  518. return false;
  519. }
  520. $pageNo = $option['pageNo'] ? $option['pageNo'] : 0;
  521. $pageSize = $option['pageSize'] ?$option['pageSize']: 6000;
  522. $startTime = isset($option['startTime']) ? $option['startTime'] * 1000 : '';
  523. $endTime = isset($option['endTime']) ? $option['endTime'] * 1000 : '';
  524. $positionTypes = $option['positionTypes'] ? $option['positionTypes']: '';
  525. $headers[] = "Content-Type: application/json";
  526. $headers[] = "Authorization: ". $tokenInfo['token'];
  527. $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;
  528. //var_dump($url);
  529. $response = $this->http_get($url, $headers);
  530. if (!$response) {
  531. $this->push_log('thirdapi_devicelocation_curl_error', $response);
  532. return false;
  533. }
  534. return json_decode($response, true);
  535. }
  536. private function getThirdLocation( $imei ){
  537. if (!$imei) {
  538. $this->push_log('third_newlocation_curl_error', 'imei 为空');
  539. return false;
  540. }
  541. $tokenInfo = $this->getThirdTokenInfo();
  542. if(!$tokenInfo){
  543. return false;
  544. }
  545. $headers[] = "Content-Type: application/json";
  546. $headers[] = "Authorization: ". $tokenInfo['token'];
  547. $url = 'http://rinlink-a18.beijing-cn-k8s-test.rinlink.com/devicedata/location/'.$imei;
  548. $response = $this->http_get($url, $headers);
  549. if (!$response) {
  550. $this->push_log('third_lastLocation_error', $response);
  551. return false;
  552. }
  553. return json_decode($response, true);
  554. }
  555. private function http_get( $url, $headers ){
  556. $oCurl = curl_init();
  557. if(!$headers){
  558. $headers = [];
  559. }
  560. if(stripos($url,"https://")!==FALSE){
  561. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  562. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
  563. }
  564. curl_setopt($oCurl, CURLOPT_URL, $url);
  565. curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers );
  566. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  567. $sContent = curl_exec($oCurl);
  568. $aStatus = curl_getinfo($oCurl);
  569. if(intval($aStatus["http_code"])==200){
  570. curl_close($oCurl);
  571. return $sContent;
  572. }else{
  573. $this->push_log('thirdapi_token_curl_error',curl_error($oCurl));
  574. curl_close($oCurl);
  575. return false;
  576. }
  577. }
  578. public function sendSmsCode( ){
  579. header('Access-Control-Allow-Origin: *');
  580. $postData = json_decode(file_get_contents('php://input'), true) ?:[];
  581. if (!$postData['phone']) {
  582. json_fail('手机号码不能为空');
  583. }
  584. if (!preg_match('/^1[3456789]\d{9}$/', $postData['phone'])) {
  585. json_fail('手机号码格式不正确');
  586. }
  587. // 是否重置密码
  588. $isReset = $postData['isReset'];
  589. if ($postData['userType'] == 'personal') { // 个人用户
  590. $identify = 'personal';
  591. } elseif ($postData['userType'] == 'group' && $postData['deviceType'] == 'badge') { // 团体徽章用户
  592. $identify = 'group_badge_user';
  593. } elseif ($postData['userType'] == 'group' && $postData['deviceType'] == 'card') { // 团体卡牌用户
  594. $identify = 'group_card_user';
  595. } else {
  596. json_fail('暂不支持的用户类型');
  597. }
  598. // 注册时检测
  599. if (!$isReset && $identify == 'group_card_user') {
  600. json_fail('暂不支持的注册用户类型');
  601. }
  602. // 获取角色id
  603. $roleId = M('roles')->where(['identify' => $identify])->getField('id');
  604. // 判断角色、号码是否已注册
  605. $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();
  606. // 重置密码时
  607. if ($isReset && empty($userinfo)) {
  608. json_fail('该号码未注册');
  609. } elseif (!$isReset && $userinfo) {
  610. json_fail('该号码已注册');
  611. }
  612. $sms_code_mode = M('sms_verification_code'); // 短信验证码模型
  613. // 防盗刷IP地址检测
  614. $todayTime = strtotime(date('Y-m-d'));
  615. $where = ['access_ip' => $_SERVER['REMOTE_ADDR'], 'created_at' => ['GT', $todayTime]];
  616. $count = $sms_code_mode->where($where)->count();
  617. if ($count >= 10) {
  618. json_fail('已达到当日获取次数上限');
  619. }
  620. // 获取短信配置
  621. $rlyunId = M('sms_config')->where(['name' => 'rlyun'])->getField('id');
  622. $smsConfig = M('sms_config')->where(['pid' => $rlyunId])->getField('key,value');
  623. if (empty($smsConfig)) {
  624. json_fail('获取短信配置失败');
  625. }
  626. // 获取短信验证码模板信息
  627. $where = ['operator' => 'rlyun', 'code' => 'verification_code'];
  628. $tmpInfo = M('sms_template')->where($where)->find();
  629. if (empty($tmpInfo)) {
  630. json_fail('获取短信验证码模板信息失败');
  631. }
  632. // 生成验证码
  633. $code = rand(0, 9999);
  634. $code = str_pad($code, 4, '0',STR_PAD_LEFT);
  635. // 保存验证码
  636. $time = time();
  637. $saveData = [
  638. 'mobile' => $postData['phone'],
  639. 'code' => $code,
  640. 'access_ip' => $_SERVER['REMOTE_ADDR'],
  641. 'created_at' => $time,
  642. 'updated_at' => $time,
  643. ];
  644. M()->startTrans(); // 开启事务
  645. $res = $sms_code_mode->createAdd($saveData);
  646. if ($res === false) {
  647. M()->rollback();
  648. json_fail('发送失败,请稍后重试');
  649. }
  650. //M()->commit();
  651. //json_success('测试,不发短信,看数据库');
  652. // 发送短信验证码
  653. $content = str_replace('{1}', $code, $tmpInfo['content']);
  654. $content = str_replace('{2}', '5分钟', $content);
  655. $contentData = [
  656. 'tplno' => $tmpInfo['identify'],
  657. 'tpldata' => [ $code, '5分钟' ],
  658. //'tpldata' => $content, // error test
  659. 'info' => $content,
  660. ];
  661. //$res = (new \Jms\Sms\RlyuntxV100)->send($postData['phone'], $contentData, $smsConfig);
  662. $res = send_sms_with_config($postData['phone'], $contentData, $smsConfig);
  663. if (!$res['success']) {
  664. M()->rollback();
  665. $res = M('sms_send_log')->add($res['data']);
  666. json_fail($res['message'] ?: '发送失败');
  667. }
  668. M()->commit();
  669. json_success($res['message']);
  670. }
  671. public function getAlarmTypeOptions( ){
  672. header('Access-Control-Allow-Origin: *');
  673. $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id');
  674. $options = M('sys_dict_data')->field('id, value as text, code as value')->where(['type_id' => $typeid])->select();
  675. if(!$options){
  676. json_fail('获取告警选项失败');
  677. }
  678. json_success('获取选项成功', $options);
  679. //AlarmType
  680. }
  681. private function isValidSmsCode( $mobile, $code ){
  682. if (!$mobile) {
  683. return ['success' => false, 'message' => '手机号码不存在'];
  684. }
  685. if (!$code) {
  686. return ['success' => false, 'message' => '验证码不存在'];
  687. }
  688. // 根据手机号码和验证码查询最后一次验证码
  689. $sms_verification_code_model = M('sms_verification_code');
  690. $cond = [ 'mobile' => $mobile, 'code' => $code ];
  691. $info = $sms_verification_code_model->where($cond)->order('created_at', 'desc')->find();
  692. // 不存在
  693. if (empty($info)) {
  694. return ['success' => false, 'message' => '验证失败,请确保手机号码和验证码输入无误'];
  695. }
  696. // 超过时间(暂定5分钟)
  697. $valid_time = 60 * 5;
  698. if (time() - $info['created_at'] > $valid_time) {
  699. return ['success' => false, 'message' => '验证码已失效'];
  700. }
  701. // 超过使用次数(暂定3次)
  702. if ($info['use_times'] >= 3) {
  703. return ['success' => false, 'message' => '验证码已失效'];
  704. }
  705. // 可以使用,使用次数+1
  706. $cond = ['id' => $info['id']];
  707. $res = $sms_verification_code_model->where($cond)->setInc('use_times');
  708. if ($res === false) {
  709. return ['success' => false, 'message' => '操作失败,请重试'];
  710. }
  711. return ['success' => true, 'message' => '验证码有效'];
  712. }
  713. public function userBindDevice( ){
  714. header('Access-Control-Allow-Origin: *');
  715. $openid = I('get.openid');
  716. $userid = I('get.userid');
  717. //检测登录状态
  718. $res=$this->checkLoginState($openid,$userid);
  719. if(!$res['status']){
  720. json_fail($res['message']);
  721. }
  722. // 通过手机号和短信验证码注册
  723. $data = json_decode( file_get_contents("php://input") ,true);
  724. // 用户类型:个人(personal)、团体(group)
  725. $userType = $data['userType'];
  726. // 设备类型:卡牌(card)、徽章(badge)
  727. $deviceType = $data['deviceType'];
  728. // 团体卡牌用户(group_card_user) 不可注册
  729. // 个人用户(personal),团体徽章用户(group_badge_user) 可注册
  730. if ($userType == 'personal') { // 个人用户
  731. $identify = 'personal';
  732. } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户
  733. $identify = 'group_badge_user';
  734. } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户
  735. $identify = 'group_card_user';
  736. } else {
  737. json_fail('未知用户类型');
  738. }
  739. if ($identify == 'group_card_user') {
  740. json_fail('无绑定设备权限');
  741. }
  742. //$data['imei'],$data['user_no'],$data['username']
  743. if(!$data['imei'] ){
  744. json_fail('缺少IMEI参数');
  745. }
  746. //先查询设备信息 看是否被绑定
  747. $where = array('imei'=>$data['imei']);
  748. $device_info=M('devices')->where($where)->find();
  749. if(!$device_info){
  750. json_fail('设备不存在,请确认输入无误');
  751. }
  752. if($device_info['user_id']){
  753. json_fail('设备已被绑定');
  754. }
  755. if ($identify == 'group_badge_user' && $device_info['device_type'] != 1 ) {
  756. json_fail('无法绑定该类型的设备');
  757. }
  758. $userType = $data['userType'];
  759. $device_name = '';
  760. if ($data['device_name']) {
  761. $device_name = $data['device_name'];
  762. } elseif ($data['username']) {
  763. $device_name = $data['username'];
  764. } else {
  765. $device_name = '用户'. substr($data['imei'], -4);
  766. }
  767. $save_data=array(
  768. 'device_name' => $device_name,
  769. 'user_id'=>$userid,
  770. 'use_state'=>1,
  771. );
  772. M()->startTrans();
  773. if ($identify == 'group_badge_user'){
  774. //团体用户 绑定设备 并绑定用户信息
  775. if( !$data['user_no'] || !$data['username'] ){
  776. json_fail('用户姓名和编号不能为空');
  777. }
  778. // 第一次绑定:将 badgeuser 中的 department_id 赋给 users 的 department_id,之后将只能绑定该部门下的设备
  779. // badge_cond
  780. $badge_cond = ['user_no'=>$data['user_no'], 'username'=>$data['username']];
  781. $userinfo = M('users')->where(['id'=>$userid])->find();
  782. if ($userinfo['department_id']) {
  783. $badge_cond['department_id'] = $userinfo['department_id'];
  784. }
  785. $badge_info = M('badgeuser')->where($badge_cond)->find();
  786. if(!$badge_info){
  787. json_fail('绑定用户不存在');
  788. }
  789. if ($badge_info['is_used']) {
  790. json_fail('该用户已绑定');
  791. }
  792. // 检测设备与用户是否在同一部门
  793. if ($device_info['department_id'] != $badge_info['department_id']) {
  794. json_fail('用户与设备所属部门不一致');
  795. }
  796. $update_data=array('is_used'=>1);
  797. //$badgeRes=M('badgeuser')->createSave(array('id'=>$badge_info['uid']),$update_data);
  798. // 修改徽章用户状态
  799. $badgeRes = M('badgeuser')->where(array('id'=>$badge_info['id']))->setField($update_data);
  800. if(!$badgeRes){
  801. M()->rollback();
  802. json_fail('绑定用户失败');
  803. }
  804. $save_data['badge_user_id']=$badge_info['id'];
  805. // 设置登录用户部门
  806. if (!$userinfo['department_id']) {
  807. $res = M('users')->where(['id'=>$userid])->setField(['department_id'=>$badge_info['department_id']]);
  808. if($res === false){
  809. M()->rollback();
  810. json_fail('设置用户部门失败');
  811. }
  812. }
  813. }
  814. $devRes=M('devices')->createSave(array('id'=>$device_info['id']),$save_data);
  815. if(!$devRes){
  816. M()->rollback();
  817. json_fail('绑定设备失败');
  818. }
  819. //未同步设备需要先同步
  820. if($device_info['sync_status']!=1){
  821. $result=$this->addToVoiceCenter($device_info['imei']);
  822. if(!$result['success']){
  823. create_log($device_info['imei'].'绑定时同步失败 message: '.$result['messaget'], 'AddVoiceCenter');
  824. M()->rollback();
  825. json_fail('绑定设备失败');
  826. }
  827. }
  828. M()->commit();
  829. json_success('绑定成功',$userid);
  830. }
  831. public function getUserFences( ){
  832. //user_has_students
  833. header('Access-Control-Allow-Origin: *');
  834. $userid =intval(I('get.userid'));
  835. if(!$userid){
  836. json_fail('获取不到你的用户标识,请重新登陆');
  837. }
  838. $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';
  839. $res = M('fences')->field($field)->where(['creator_id' => $userid, 'fence_type' => 1])->select();
  840. if(!$res){
  841. json_fail('查询不到用户围栏');
  842. }
  843. foreach($res as &$v){
  844. $v['inFenceAlarm'] = (bool)($v['inFenceAlarm']);
  845. $v['outFenceAlarm'] = (bool)($v['outFenceAlarm']);
  846. $v['fenceInfo'] = json_decode($v['fenceInfo'], true);
  847. $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($v['fenceInfo']['center']['lat'], $v['fenceInfo']['center']['lng']);
  848. $v['fenceInfo']['center']['lat'] = $convPoint['lat'];
  849. $v['fenceInfo']['center']['lng'] = $convPoint['lng'];
  850. }
  851. json_success('查询成功', $res);
  852. }
  853. public function changeUserFenceAlarmStatus( ){
  854. //user_has_students
  855. header('Access-Control-Allow-Origin: *');
  856. $post_data = file_get_contents('php://input');
  857. $post_data = json_decode($post_data, true);
  858. $fenceId = $post_data['id'];
  859. if(!$fenceId){
  860. json_fail('获取不到围栏标识,请刷新下');
  861. }
  862. $alarmType = $post_data['alarmType'];
  863. $value = $post_data['value'];
  864. if(is_null($value) ){
  865. json_fail('获取不到告警标识值');
  866. }
  867. $saveData = [];
  868. if($alarmType == 'in'){
  869. $saveData['is_check_in'] = $value;
  870. }else{
  871. $saveData['is_check_out'] = $value;
  872. }
  873. $res = M('fences')->where(['id' => $fenceId])->save($saveData);
  874. if(!res){
  875. json_fail('修改告警状态失败');
  876. }
  877. json_success('修改告警状态成功');
  878. }
  879. public function updateDeviceInfo( ){
  880. header('Access-Control-Allow-Origin: *');
  881. $openid = I('get.openid');
  882. $userid = I('get.userid');
  883. //检测登录状态
  884. $res=$this->checkLoginState($openid,$userid);
  885. if(!$res['status']){
  886. json_fail($res['message']);
  887. }
  888. $data = json_decode( file_get_contents("php://input") ,true);
  889. $device_id=$data['device_id'];
  890. if(!$device_id){
  891. json_fail('缺少设备ID');
  892. }
  893. $device_name=$data['device_name'];
  894. if(!$device_name){
  895. json_fail('缺少修改信息');
  896. }
  897. $cond=array('id'=>$device_id);
  898. $res=M('devices')->createSave($cond,array('device_name'=>$device_name));
  899. if(!$res){
  900. json_fail('修改失败');
  901. }
  902. json_success('修改成功',$list);
  903. }
  904. public function getSystemFences( ){
  905. //user_has_students
  906. header('Access-Control-Allow-Origin: *');
  907. $userid =intval(I('get.userid'));
  908. if(!$userid){
  909. json_fail('获取不到你的用户标识,请重新登陆');
  910. }
  911. $userBelongDep = M('users')->where(['id' => $userid ])->getField('department_id');
  912. if(!$userBelongDep){
  913. json_fail('查询不到用户归属组织');
  914. }
  915. $departIds = M('departments')->where(['id' => $userBelongDep ])->getField('level');
  916. if($departIds){
  917. $departIds = explode('-', $departIds);
  918. }else{
  919. $departIds =[];
  920. }
  921. array_push($departIds, $userBelongDep);
  922. $typeid = M('sys_dict_type')->where(['code' =>'FenceType'])->getField('id');
  923. $fenceTypeAssoc = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value');
  924. $fenceCond = [
  925. 'fence_type' => ['in', [0, 2]],
  926. 'departments' => ['in', $departIds]
  927. ];
  928. $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';
  929. $res = M('fences')->field($field)
  930. ->join('departments on fences.departments = departments.id')
  931. ->where($fenceCond)
  932. ->select();
  933. if(!$res){
  934. json_fail('查询不到系统围栏');
  935. }
  936. foreach($res as &$v){
  937. $v['inFenceAlarm'] = (bool)($v['inFenceAlarm']);
  938. $v['outFenceAlarm'] = (bool)($v['inFenceAlarm']);
  939. $v['fence_type_text'] = $fenceTypeAssoc[$v['fence_type']];
  940. }
  941. json_success('查询成功', $res);
  942. }
  943. public function userUnbindDevice( ){
  944. header('Access-Control-Allow-Origin: *');
  945. $openid = I('get.openid');
  946. $userid = I('get.userid');
  947. //检测登录状态
  948. $res=$this->checkLoginState($openid,$userid);
  949. if(!$res['status']){
  950. json_fail($res['message']);
  951. }
  952. // 通过手机号和短信验证码注册
  953. $data = json_decode( file_get_contents("php://input") ,true);
  954. //$data['imei'],$data['user_no'],$data['username']
  955. //先查询设备信息 看是否被绑定
  956. if(!$data['device_id']){
  957. json_fail('缺少设备ID参数');
  958. }
  959. $device_info=M('devices')->where(array('id'=>$data['device_id']))->find();
  960. if(!$device_info){
  961. json_fail('设备不存在,请确认输入无误');
  962. }
  963. $save_data=array(
  964. 'user_id'=>'',
  965. 'badge_user_id'=>'',
  966. 'use_state'=>0,
  967. );
  968. M()->startTrans();
  969. if($device_info['badge_user_id']){
  970. $badRes=M('badgeuser')->createSave(array('id'=>$device_info['badge_user_id']),array('is_used'=>0));
  971. if(!$badRes){
  972. json_fail('解绑失败');
  973. }
  974. }
  975. $devRes=M('devices')->createSave(array('id'=>$device_info['id']),$save_data);
  976. if(!$devRes){
  977. M()->rollback();
  978. json_fail('解绑失败');
  979. }
  980. // 如果没有设备了,置空 department_id
  981. if (!M('devices')->where(['user_id'=>$userid])->count()) {
  982. $res = M('users')->where(['id'=>$userid])->setField(['department_id'=>'']);
  983. if($res === false){
  984. M()->rollback();
  985. json_fail('解绑失败2');
  986. }
  987. }
  988. M()->commit();
  989. json_success('解绑成功',$userid);
  990. }
  991. public function addUserFence( ){
  992. //user_has_students
  993. header('Access-Control-Allow-Origin: *');
  994. $data = json_decode( file_get_contents("php://input") ,true);
  995. $userid =intval($data['userid']);
  996. if(!$userid){
  997. json_fail('获取不到你的用户标识,请重新登陆');
  998. }
  999. $fenceName = $data['fenceName'];
  1000. if(!$fenceName){
  1001. json_fail('获取不到围栏名');
  1002. }
  1003. $fenceInfo = $data['fenceInfo'];
  1004. if(!$fenceInfo){
  1005. json_fail('获取不到围栏信息');
  1006. }
  1007. $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($fenceInfo['center']['lat'], $fenceInfo['center']['lng']);
  1008. $fenceInfo['center']['lat'] = $convPoint['lat'];
  1009. $fenceInfo['center']['lng'] = $convPoint['lng'];
  1010. $saveData = [
  1011. 'creator_id' => $userid,
  1012. 'name' => $fenceName,
  1013. 'push_users' => json_encode([$userid]),
  1014. 'fence_shape' => 'circle',
  1015. 'fence_type' => 1,
  1016. 'fence_info' => json_encode($fenceInfo),
  1017. 'created_at' => time(),
  1018. 'created_at' => time()
  1019. ];
  1020. $res = M('fences')->add($saveData);
  1021. if(!$res){
  1022. json_fail('保存入库失败');
  1023. }
  1024. json_success('保存入库成功');
  1025. }
  1026. private function getWeixinAccessToken( ){
  1027. $token = (new \Jiaruan\WxTmp())->getAccessToken();
  1028. return $token;
  1029. /*
  1030. $appid= C('WECHAT_APPID');
  1031. $appSecret = C('WECHAT_APPSECRET');
  1032. $accessToken = S('wx_pub_accessToken');
  1033. if(!$accessToken){
  1034. $ch = curl_init();
  1035. curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appSecret);
  1036. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1037. $output = json_decode(curl_exec($ch), true);
  1038. curl_close($ch);
  1039. if($output['errcode']){
  1040. return $output;
  1041. }
  1042. S('wx_pub_accessToken', $output['access_token'], '7100');
  1043. return $output['access_token'];
  1044. }else{
  1045. return $accessToken;
  1046. }
  1047. */
  1048. }
  1049. public function getAlarmRecords( ){
  1050. header('Access-Control-Allow-Origin: *');
  1051. $post_data = json_decode(file_get_contents('php://input'), true);
  1052. $openid = $post_data['openid'];
  1053. $userid = $post_data['userid'];
  1054. //检测登录状态
  1055. $res = $this->checkLoginState($openid,$userid);
  1056. if(!$res['status']){
  1057. json_fail($res['message']);
  1058. }
  1059. // 获取登录账号部门下所有告警状态的学生数据
  1060. $user_model = M('users');
  1061. $where = ['id' => $userid];
  1062. $userinfo = $user_model->field('id,department_id')->where($where)->find();
  1063. // 获取权限范围内的用户id
  1064. $creator_ids = $this->getRightCreatorIds($userinfo);
  1065. if ($creator_ids === false) {
  1066. json_fail('获取数据失败');
  1067. }
  1068. $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
  1069. $page = isset($post_data['page']) ? $post_data['page'] : 1;
  1070. // 告警记录条件
  1071. // 初始化条件
  1072. $cond = [];
  1073. $reason = I('get.reason');
  1074. $state = I('get.state');
  1075. $result = I('get.result');
  1076. if ($reason) {
  1077. if ($reason == 'fence') {
  1078. $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out']];
  1079. } else {
  1080. $cond['alarm_reason'] = $reason;
  1081. }
  1082. } else {
  1083. // 默认只显示 SOS 和围栏告警记录
  1084. $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out', 'press']];
  1085. }
  1086. if ($state) {
  1087. $cond['state'] = $state;
  1088. }
  1089. if ($result !== '' && is_numeric($result)) {
  1090. $cond['result'] = $result;
  1091. }
  1092. if (is_array($creator_ids)) {
  1093. $cond['creator_id'] = ['IN', $creator_ids];
  1094. }
  1095. // 查出总数量
  1096. $list = [];
  1097. $total = M('alarm_records')->where($cond)->count();
  1098. if ($total) {
  1099. if ($state == 'start' || $state == 'end') {
  1100. $order = "{$state}_time desc";
  1101. } else {
  1102. $order = 'id desc';
  1103. }
  1104. $fields = 'id,device_number,alarm_reason,handler_id,start_time,end_time,state,comment,result';
  1105. $list = M('alarm_records')->field($fields)->where($cond)->limit($limit)->page($page)->order($order)->select() ?: [];
  1106. if (!empty($list)) {
  1107. // alarm_reason,handler_id,result
  1108. // 获取告警类型
  1109. $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id');
  1110. $reason_arr = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value');
  1111. // 处理结果
  1112. $result_arr = [
  1113. 0 => '待处理',
  1114. 1 => '已处理',
  1115. 2 => '误报',
  1116. ];
  1117. // 中文转换
  1118. foreach ($list as &$alarm) {
  1119. $alarm['start_time'] = $alarm['start_time'] ? date('Y-m-d H:i:s', $alarm['start_time']) : '';
  1120. $alarm['end_time'] = $alarm['end_time'] ? date('Y-m-d H:i:s', $alarm['end_time']) : '';
  1121. if (is_array($reason_arr)) {
  1122. $alarm['alarm_reason'] = $reason_arr[$alarm['alarm_reason']];
  1123. }
  1124. if (is_numeric($alarm['result'])) {
  1125. $alarm['result'] = $result_arr[$alarm['result']];
  1126. }
  1127. }
  1128. }
  1129. }
  1130. // 返回
  1131. $data = [
  1132. 'total' => $total,
  1133. 'limit' => $limit,
  1134. 'page' => $page,
  1135. 'list' => $list,
  1136. ];
  1137. json_success('获取成功', $data);
  1138. }
  1139. public function getAlarmDetail( ){
  1140. header('Access-Control-Allow-Origin: *');
  1141. $openid = I('get.openid');
  1142. $userid = I('get.userid');
  1143. if(!$userid || $userid == 'undefined' || $userid == 'null'){
  1144. json_fail('获取不到你的用户标识,请重新登陆');
  1145. }
  1146. //检测登录状态
  1147. $res = $this->checkLoginState($openid,$userid);
  1148. if(!$res['status']){
  1149. json_fail($res['message']);
  1150. }
  1151. $alarm_id = I('get.id');
  1152. if (!$alarm_id) {
  1153. json_fail('获取告警信息失败1');
  1154. }
  1155. // 查出告警数据
  1156. $where = ['id' => $alarm_id];
  1157. $alarm_info = M('alarm_records')->where($where)->find();
  1158. if (empty($alarm_info)) {
  1159. json_fail('获取告警信息失败2');
  1160. }
  1161. $report_id = I('get.rid');
  1162. if (!$report_id) {
  1163. json_fail('获取告警信息失败3');
  1164. }
  1165. $where = ['id' => $report_id];
  1166. $alarm_report = M('alarm_report')->where($where)->find();
  1167. if (empty($alarm_report)) {
  1168. json_fail('获取告警信息失败4');
  1169. }
  1170. $alarm_info['address']=$alarm_report['address'];
  1171. // 查出设备信息
  1172. $where = ['imei' => $alarm_info['device_number']];
  1173. $device_info = M('devices')->where($where)->find();
  1174. if (empty($alarm_info)) {
  1175. json_fail('获取告警设备信息失败');
  1176. }
  1177. if ($device_info['online_time'] > $device_info['wifi_online_time']) {
  1178. $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']);
  1179. $device_info['last_location'] = $device_info['longitude'] .','. $device_info['latitude'];
  1180. $res = bmap_geocoding($device_info['latitude'], $device_info['longitude']);
  1181. if($res['success']){
  1182. $device_info['address'] = $res['address'];
  1183. }else{
  1184. $device_info['address']='';
  1185. }
  1186. } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) {
  1187. $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']);
  1188. $device_info['last_location'] = $device_info['wifi_longitude'] .','. $device_info['wifi_latitude'];
  1189. } else {
  1190. $device_info['last_online_time'] = '0000-00-00 00:00:00';
  1191. $device_info['last_location'] = '';
  1192. $device_info['address']='';
  1193. }
  1194. // 查出设备用户
  1195. if ($device_info['badge_user_id']) {
  1196. $where = ['id' => $device_info['badge_user_id']];
  1197. $user_info = M('badgeuser')->where($where)->find() ?: [];
  1198. } else {
  1199. $where = ['id' => $device_info['user_id']];
  1200. $user_info = M('users')->where($where)->find() ?: [];
  1201. }
  1202. //if (empty($user_info)) {
  1203. //json_fail('获取告警用户信息失败');
  1204. //}
  1205. // 获取紧急联系人
  1206. $where = ['device_id' => $device_info['id']];
  1207. $urgent_list = M('kq_urgent')->where($where)->select() ? : [];
  1208. if (!empty($urgent_list)) {
  1209. $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id');
  1210. $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value');
  1211. foreach ($urgent_list as $key => &$urgent) {
  1212. $urgent['relationship_text'] = $ships[$urgent['relationship']];
  1213. }
  1214. }
  1215. // 部门名称
  1216. $alarm_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name');
  1217. $alarm_info['user_info'] = $user_info;
  1218. $alarm_info['urgent_list'] = $urgent_list;
  1219. $alarm_info['device_info'] = $device_info;
  1220. $alarm_info['device_info']['department_name'] = $alarm_info['department_name'];
  1221. json_success('获取成功', $alarm_info);
  1222. }
  1223. public function handleAlarm( ){
  1224. header('Access-Control-Allow-Origin: *');
  1225. $post_data = json_decode(file_get_contents('php://input'), true);
  1226. $openid = I('get.openid');
  1227. $userid = I('get.userid');
  1228. if(!$userid || $userid == 'undefined' || $userid == 'null'){
  1229. json_fail('获取不到你的用户标识,请重新登陆');
  1230. }
  1231. //检测登录状态
  1232. $res = $this->checkLoginState($openid,$userid);
  1233. if(!$res['status']){
  1234. json_fail($res['message']);
  1235. }
  1236. // result 1-出警,2-误报
  1237. if (!$post_data['result']) {
  1238. json_fail('处理结果不能为空');
  1239. }
  1240. if (!$post_data['comment']) {
  1241. json_fail('处理原因不能为空');
  1242. }
  1243. if (!$post_data['id']) {
  1244. json_fail('未获取到告警信息1');
  1245. }
  1246. $time = time();
  1247. M()->startTrans();
  1248. // 修改前,检测结果是否一致,如果一致不允许重复操作
  1249. $records_model = M('alarm_records');
  1250. $where = ['id' => $post_data['id']];
  1251. $record_info = $records_model->where($where)->field('device_number,result')->find();
  1252. if (empty($record_info)) {
  1253. json_fail('未获取到告警信息2');
  1254. }
  1255. //if ($record_info['result'] > 0) {
  1256. if ($record_info['result'] == $post_data['result']) {
  1257. M()->rollback();
  1258. json_fail('已处理,请勿重复操作');
  1259. }
  1260. $where = ['id' => $post_data['id']];
  1261. $save_data = [
  1262. 'comment' => $post_data['comment'],
  1263. 'result' => $post_data['result'],
  1264. 'handler_id' => $userid,
  1265. 'state' => 'end',
  1266. 'end_time' => $time,
  1267. 'updated_at' => $time,
  1268. ];
  1269. $res = $records_model->createSave($where, $save_data);
  1270. if ($res === false) {
  1271. M()->rollback();
  1272. json_fail('操作失败');
  1273. }
  1274. // 查出设备告警状态
  1275. $where = ['imei' => $record_info['device_number']];
  1276. $device_info = M('devices')->where($where)->field('id,alarm_state')->find();
  1277. if ($device_info['alarm_state'] > 0) {
  1278. // 修改设备状态
  1279. $where = ['id' => $device_info['id']];
  1280. $res = M('devices')->where($where)->setField('alarm_state', 0);
  1281. if (!$res) {
  1282. M()->rollback();
  1283. json_fail('修改设备状态失败');
  1284. }
  1285. }
  1286. M()->commit();
  1287. json_success('操作成功');
  1288. }
  1289. public function editYysProfile( ){
  1290. header('Access-Control-Allow-Origin: *');
  1291. $openid = I('get.openid');
  1292. $userid = I('get.userid');
  1293. //检测登录状态
  1294. $res = $this->checkLoginState($openid,$userid);
  1295. if(!$res['status']){
  1296. json_fail($res['message']);
  1297. }
  1298. $data = json_decode( file_get_contents("php://input") ,true);
  1299. $data = array_map(function($item){
  1300. return trim($item);
  1301. }, $data);
  1302. if (!$data['nickName']) {
  1303. json_fail('昵称不能为空');
  1304. }
  1305. if (!$data['phone']) {
  1306. json_fail('手机号码不能为空');
  1307. }
  1308. if (!preg_match('/^[-_a-zA-Z0-9]{6,16}?$/', $data['phone'])) {
  1309. json_fail('手机号码格式不正确');
  1310. }
  1311. // 修改密码
  1312. if ($data['oldPwd']) {
  1313. if (!$data['newPwd']) {
  1314. json_fail('新密码不能为空');
  1315. }
  1316. if (!$data['confirmNewPwd']) {
  1317. json_fail('确认密码不能为空');
  1318. }
  1319. if ($data['newPwd'] != $data['confirmNewPwd']) {
  1320. json_fail('两次新密码不一致');
  1321. }
  1322. }
  1323. $userCond = array( 'id' => $userid);
  1324. $user_info = M('users')->where($userCond)->find();
  1325. if(!$user_info){
  1326. json_fail('获取用户信息失败');
  1327. }
  1328. if ($user_info['wx_open_id'] != $openid) {
  1329. json_fail('账号可能被其他用户登录,请重新登录');
  1330. }
  1331. if ($data['oldPwd']) {
  1332. if(!password_verify($data['oldPwd'], $user_info['password'])){
  1333. json_fail('原密码不正确');
  1334. }
  1335. }
  1336. $saveData = [
  1337. 'realname' => $data['nickName'],
  1338. 'phone' => $data['phone'],
  1339. ];
  1340. // 有原密码才能修改
  1341. if ($data['oldPwd']) {
  1342. $saveData['password'] = password_hash($data['newPwd'], PASSWORD_DEFAULT);
  1343. }
  1344. $result = M('users')->createSave($userCond, $saveData);
  1345. if(!$result){
  1346. json_fail('修改失败');
  1347. }
  1348. $respData = [
  1349. 'id' => $user_info['id'],
  1350. 'realname' => $data['nickName'],
  1351. 'avatar' => $user_info['avatar'],
  1352. 'phone' => $data['phone'],
  1353. ];
  1354. json_success('修改成功', $respData);
  1355. }
  1356. public function changeAuthorize( ){
  1357. //user_has_students
  1358. header('Access-Control-Allow-Origin: *');
  1359. $imei = I('get.imei');
  1360. if(!$imei){
  1361. json_fail('获取不到设备号');
  1362. }
  1363. $authorize = intval(I('get.authorize') );
  1364. if($authorize !== 0 && $authorize !== 1){
  1365. json_fail('授权状态值不合法');
  1366. }
  1367. $saveData = [
  1368. 'authorize' => $authorize,
  1369. 'updated_at' => time()
  1370. ];
  1371. $res = M('devices')->where(['imei' => $imei])->save($saveData);
  1372. if(!res){
  1373. json_fail('权限修改失败');
  1374. }
  1375. json_success('权限修改成功');
  1376. }
  1377. public function getDeviceInfoSingle( ){
  1378. //user_has_students
  1379. header('Access-Control-Allow-Origin: *');
  1380. $imei = I('get.imei');
  1381. if(!$imei){
  1382. json_fail('获取不到设备号');
  1383. }
  1384. $res = M('devices')->where(['imei' => $imei])->find();
  1385. if(!res){
  1386. json_fail('获取设备信息失败');
  1387. }
  1388. json_success('获取设备信息成功', $res);
  1389. }
  1390. public function getDevices( ){
  1391. // 获取登录用户信息
  1392. $userinfo = $this->getYysLoginUserinfo();
  1393. // 获取权限范围内的用户id
  1394. $creator_ids = $this->getRightCreatorIds($userinfo);
  1395. if ($creator_ids === false) {
  1396. json_fail('获取失败');
  1397. }
  1398. // 获取 POST 数据
  1399. $post_data = json_decode(file_get_contents('php://input'), true);
  1400. $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
  1401. $page = isset($post_data['page']) ? $post_data['page'] : 1;
  1402. $imei = $post_data['imei'];
  1403. $list = [];
  1404. $cond = [];
  1405. $devices_model = M('devices');
  1406. // 查出总数量
  1407. if (is_array($creator_ids)) {
  1408. $cond['creator_id'] = ['IN', $creator_ids];
  1409. }
  1410. if ($imei) {
  1411. $cond['imei'] = ['LIKE', "%{$imei}%"];
  1412. }
  1413. $total = $devices_model->where($cond)->count();
  1414. if ($total) {
  1415. $list = $devices_model->where($cond)->limit($limit)->page($page)->select() ?: [];
  1416. }
  1417. // 返回
  1418. $data = [
  1419. 'total' => $total,
  1420. 'limit' => $limit,
  1421. 'page' => $page,
  1422. 'list' => $list,
  1423. ];
  1424. json_success('获取成功', $data);
  1425. }
  1426. private function getYysLoginUserinfo( ){
  1427. header('Access-Control-Allow-Origin: *');
  1428. $openid = I('get.openid');
  1429. if(!$openid){
  1430. json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
  1431. }
  1432. // 微信运营角色
  1433. $where = ['identify' => 'wxyy'];
  1434. $role_id = M('roles')->where($where)->getField('id');
  1435. if (!$role_id) {
  1436. json_fail('未开放微信运营角色');
  1437. }
  1438. // 获取登录账号信息
  1439. $userid = I('get.userid');
  1440. $cond = [
  1441. //'u.wx_open_id' => $openid,
  1442. 'u.id' => $userid,
  1443. ];
  1444. //$userinfo = M('users')->field('id,department_id')->where($where)->find();
  1445. $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();
  1446. if (!$userinfo) {
  1447. json_fail('获取用户信息失败,请重新登录');
  1448. }
  1449. if ($userinfo['wx_open_id'] != $openid) {
  1450. json_fail('账号可能在其他设备登录,请重新登录');
  1451. }
  1452. return $userinfo;
  1453. }
  1454. public function getDeviceDetail( ){
  1455. header('Access-Control-Allow-Origin: *');
  1456. $userid = I('get.userid');
  1457. if(!$userid || $userid == 'undefined' || $userid == 'null'){
  1458. json_fail('未获取到用户标识,请重新登陆');
  1459. }
  1460. $id = I('get.id');
  1461. if (!$id) {
  1462. json_fail('获取设备信息失败');
  1463. }
  1464. $openid = I('get.openid');
  1465. //检测登录状态
  1466. $res = $this->checkLoginState($openid, $userid);
  1467. if(!$res['status']){
  1468. json_fail($res['message']);
  1469. }
  1470. // 检测是否在查询权限范围
  1471. // 查出设备信息
  1472. $where = ['id' => $id];
  1473. $device_info = M('devices')->where($where)->find() ? : [];
  1474. if (empty($device_info)) {
  1475. json_fail('未获取到设备信息');
  1476. }
  1477. if ($device_info['online_time'] >= $device_info['wifi_online_time']) {
  1478. $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']);
  1479. $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($device_info['latitude'],$device_info['longitude']);
  1480. $device_info['last_location'] = $convPoint['lng'] .','. $convPoint['lat'];
  1481. } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) {
  1482. $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']);
  1483. $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($device_info['wifi_latitude'],$device_info['wifi_longitude']);
  1484. $device_info['last_location'] = $convPoint['lng'] .','. $convPoint['lat'];
  1485. } else {
  1486. $device_info['last_online_time'] = '0000-00-00 00:00:00';
  1487. $device_info['last_location'] = '';
  1488. }
  1489. // 查出设备用户
  1490. if ($device_info['badge_user_id']) {
  1491. $where = ['id' => $device_info['badge_user_id']];
  1492. $user_info = M('badgeuser')->where($where)->find() ?: [];
  1493. } else {
  1494. $where = ['id' => $device_info['user_id']];
  1495. $user_info = M('users')->where($where)->find() ?: [];
  1496. }
  1497. //if (empty($user_info)) {
  1498. //json_fail('获取告警用户信息失败');
  1499. //}
  1500. // 获取紧急联系人
  1501. $where = ['device_id' => $device_info['id']];
  1502. $urgent_list = M('kq_urgent')->where($where)->select() ? : [];
  1503. if (!empty($urgent_list)) {
  1504. $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id');
  1505. $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value');
  1506. foreach ($urgent_list as $key => &$urgent) {
  1507. $urgent['relationship_text'] = $ships[$urgent['relationship']];
  1508. }
  1509. }
  1510. // 部门名称
  1511. $device_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name');
  1512. $device_info['user_info'] = $user_info;
  1513. $device_info['urgent_list'] = $urgent_list;
  1514. json_success('获取成功', $device_info);
  1515. }
  1516. public function getWaitHandleAlarmCounts( ){
  1517. // 获取登录用户信息
  1518. $userinfo = $this->getYysLoginUserinfo();
  1519. // 获取权限范围内的用户id
  1520. $creator_ids = $this->getRightCreatorIds($userinfo);
  1521. if ($creator_ids === false) {
  1522. json_fail('获取失败');
  1523. }
  1524. $cond = [
  1525. 'state' => 'start',
  1526. ];
  1527. // 查出总数量
  1528. if (is_array($creator_ids)) {
  1529. $cond['creator_id'] = ['IN', $creator_ids];
  1530. }
  1531. $fields = 'alarm_reason, count(alarm_reason) as count';
  1532. $list = M('alarm_records')->where($cond)->group('alarm_reason')->getField($fields) ?:[];
  1533. json_success('获取成功', $list);
  1534. }
  1535. public function getDevicePositionList( ){
  1536. // 获取登录用户信息
  1537. $userinfo = $this->getYysLoginUserinfo();
  1538. // 获取权限范围内的用户id
  1539. $creator_ids = $this->getRightCreatorIds($userinfo);
  1540. if ($creator_ids === false) {
  1541. json_fail('获取失败');
  1542. }
  1543. $cond = [
  1544. 'use_state' => 1,
  1545. ];
  1546. // 查出总数量
  1547. if (is_array($creator_ids)) {
  1548. $cond['creator_id'] = ['IN', $creator_ids];
  1549. }
  1550. $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';
  1551. $list = M('devices')->field($fields)->where($cond)->select() ?: [];
  1552. $resp = [];
  1553. foreach($list as &$locationInfo){
  1554. //new end
  1555. //wifi_online_time
  1556. //wifi_longitude
  1557. //wifi_latitude
  1558. //addr
  1559. $locationInfo['isAlarm'] = $locationInfo['alarm_state'];
  1560. $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ;
  1561. $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time'];
  1562. $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude'];
  1563. $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude'];
  1564. if(!$locationInfo['time']){
  1565. $locationInfo['awayTime'] = '从未在线';
  1566. }else{
  1567. $timeInterval = time() - (int)$locationInfo['time'];
  1568. $locationInfo['awayTime'] = $this->getHumenTime($timeInterval);
  1569. }
  1570. $lngLatAlter = new \Jms\Algo\Geometry();
  1571. if(!$locationInfo['lat'] || !$locationInfo['lng']){
  1572. continue;
  1573. }
  1574. $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']);
  1575. $locationInfo['lat'] = $latLng['lat'];
  1576. $locationInfo['lng'] = $latLng['lng'];
  1577. $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']);
  1578. array_push($resp, $locationInfo);
  1579. }
  1580. json_success('获取成功', $resp);
  1581. }
  1582. public function getAllFences( ){
  1583. //user_has_students
  1584. header('Access-Control-Allow-Origin: *');
  1585. $userid =intval(I('get.userid'));
  1586. if(!$userid){
  1587. json_fail('获取不到你的用户标识,请重新登陆');
  1588. }
  1589. $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';
  1590. $cond = [
  1591. 'fence_type' => 0,
  1592. 'creator_id' => $userid,
  1593. '_logic' => 'OR'
  1594. ];
  1595. $res = M('fences')->field($field)->where($cond)->select();
  1596. if(!$res){
  1597. json_fail('查询不到可见的围栏');
  1598. }
  1599. foreach($res as &$v){
  1600. $v['inAlarm'] = (bool)($v['inAlarm']);
  1601. $v['outAlarm'] = (bool)($v['outAlarm']);
  1602. $v['info'] = json_decode($v['info'], true);
  1603. }
  1604. json_success('查询成功', $res);
  1605. }
  1606. public function editUserFence( ){
  1607. //user_has_students
  1608. header('Access-Control-Allow-Origin: *');
  1609. $data = json_decode( file_get_contents("php://input") ,true);
  1610. $userid =intval($data['userid']);
  1611. if(!$userid){
  1612. json_fail('获取不到你的用户标识,请重新登陆');
  1613. }
  1614. $fenceId = intval($data['fenceId']);
  1615. $fenceName = $data['fenceName'];
  1616. if(!$fenceName){
  1617. json_fail('获取不到围栏名');
  1618. }
  1619. $fenceInfo = $data['fenceInfo'];
  1620. if(!$fenceInfo){
  1621. json_fail('获取不到围栏信息');
  1622. }
  1623. $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($fenceInfo['center']['lat'], $fenceInfo['center']['lng']);
  1624. $fenceInfo['center']['lat'] = $convPoint['lat'];
  1625. $fenceInfo['center']['lng'] = $convPoint['lng'];
  1626. $saveData = [
  1627. 'name' => $fenceName,
  1628. 'fence_shape' => 'circle',
  1629. 'fence_info' => json_encode($fenceInfo),
  1630. 'updated_at' => time()
  1631. ];
  1632. $res = M('fences')->where(['id' => $fenceId])->save($saveData);
  1633. if(!$res){
  1634. json_fail('保存入库失败');
  1635. }
  1636. json_success('保存入库成功');
  1637. }
  1638. public function getRelationshipList( ){
  1639. header('Access-Control-Allow-Origin: *');
  1640. // 查出 Relationships id
  1641. $where = array('code' => 'Relationships');
  1642. $type_id = M('sys_dict_type')->where($where)->getField('id');
  1643. if (empty($type_id)) {
  1644. json_fail('获取失败');
  1645. }
  1646. $where = array('type_id' => $type_id);
  1647. $list = M('sys_dict_data')->field('code as id, value as text')->where($where)->select();
  1648. if (empty($list)) {
  1649. json_fail('获取失败');
  1650. }
  1651. json_success('获取成功', $list);
  1652. }
  1653. public function editProfile( ){
  1654. header('Access-Control-Allow-Origin: *');
  1655. $openid = I('get.openid');
  1656. $userid = I('get.userid');
  1657. //检测登录状态
  1658. $res = $this->checkLoginState($openid,$userid);
  1659. if(!$res['status']){
  1660. json_fail($res['message']);
  1661. }
  1662. $data = json_decode( file_get_contents("php://input") ,true);
  1663. $data = array_map(function($item){
  1664. return trim($item);
  1665. }, $data);
  1666. if (!$data['nickName']) {
  1667. json_fail('昵称不能为空');
  1668. }
  1669. if (!$data['phone']) {
  1670. json_fail('手机号码不能为空');
  1671. } else {
  1672. if (!preg_match('/^[-_a-zA-Z0-9]{6,16}?$/', $data['phone'])) {
  1673. json_fail('手机号码格式不正确');
  1674. }
  1675. }
  1676. // 修改密码
  1677. if ($data['oldPwd']) {
  1678. if (!$data['newPwd']) {
  1679. json_fail('新密码不能为空');
  1680. }
  1681. if (!$data['confirmNewPwd']) {
  1682. json_fail('确认密码不能为空');
  1683. }
  1684. if ($data['newPwd'] != $data['confirmNewPwd']) {
  1685. json_fail('两次新密码不一致');
  1686. }
  1687. }
  1688. $userCond = array( 'id' => $userid);
  1689. $user_info = M('users')->where($userCond)->find();
  1690. if(!$user_info){
  1691. json_fail('获取用户信息失败');
  1692. }
  1693. if ($user_info['wx_open_id'] != $openid) {
  1694. json_fail('账号可能被其他用户登录,请重新登录');
  1695. }
  1696. if ($data['oldPwd']) {
  1697. if(!password_verify($data['oldPwd'], $user_info['password'])){
  1698. json_fail('原密码不正确');
  1699. }
  1700. }
  1701. $saveData = [
  1702. 'realname' => $data['nickName'],
  1703. 'phone' => $data['phone'],
  1704. ];
  1705. // 有原密码才能修改
  1706. if ($data['oldPwd']) {
  1707. $saveData['password'] = password_hash($data['newPwd'], PASSWORD_DEFAULT);
  1708. }
  1709. $result = M('users')->createSave($userCond, $saveData);
  1710. if(!$result){
  1711. json_fail('修改失败');
  1712. }
  1713. $respData = [
  1714. 'id' => $user_info['id'],
  1715. 'realname' => $data['nickName'],
  1716. 'avatar' => $user_info['avatar'],
  1717. 'phone' => $data['phone'],
  1718. ];
  1719. json_success('修改成功', $respData);
  1720. }
  1721. public function getLastPositionSingle( ){
  1722. header('Access-Control-Allow-Origin: *');
  1723. $imei = I('get.imei');
  1724. if(!$imei){
  1725. json_fail('服务端未检测到设备编号');
  1726. }
  1727. $locationInfo = M('devices')->where(['imei' => $imei])->find();
  1728. if(!$locationInfo){
  1729. json_fail('查询不到该设备当前信息哦!');
  1730. }
  1731. //wifi_online_time
  1732. //wifi_longitude
  1733. //wifi_latitude
  1734. //addr
  1735. $locationInfo['isAlarm'] = $locationInfo['alarm_status'];
  1736. $isWifi = $locationInfo['wifi_online_time'] > $locationInfo['online_time'] || intval($locationInfo['latitude']) < 1 ;;
  1737. $locationInfo['time'] = $isWifi ? $locationInfo['wifi_online_time'] : $locationInfo['online_time'];
  1738. $locationInfo['lat'] = $isWifi ? $locationInfo['wifi_latitude'] : $locationInfo['latitude'];
  1739. $locationInfo['lng'] = $isWifi ? $locationInfo['wifi_longitude'] : $locationInfo['longitude'];
  1740. $locationInfo['address'] = $locationInfo['address'];
  1741. //
  1742. if(!$locationInfo['time']){
  1743. $locationInfo['awayTime'] = '从未在线';
  1744. }else{
  1745. $timeInterval = time() - (int)$locationInfo['time'];
  1746. $locationInfo['awayTime'] = $this->getHumenTime($timeInterval);
  1747. }
  1748. $lngLatAlter = new \Jms\Algo\Geometry();
  1749. $latLng = $lngLatAlter->convertBd09ToGcj02($locationInfo['lat'], $locationInfo['lng']);
  1750. $locationInfo['lat'] = $latLng['lat'];
  1751. $locationInfo['lng'] = $latLng['lng'];
  1752. $locationInfo['date_time'] = date('Y-m-d H:i:s', $locationInfo['time']);
  1753. json_success('查询成功', $locationInfo);
  1754. }
  1755. public function yysLogin( ){
  1756. header('Access-Control-Allow-Origin: *');
  1757. //json_fail('登录失败');
  1758. $openid = I('get.openid');
  1759. if(!$openid){
  1760. json_fail('未授权,请关闭当前页面重新进入');
  1761. }
  1762. $data = json_decode( file_get_contents("php://input") ,true);
  1763. // 微信运营角色
  1764. $where = ['identify' => 'wxyy'];
  1765. $role_id = M('roles')->where($where)->getField('id');
  1766. if (!$role_id) {
  1767. json_fail('未开放微信运营角色');
  1768. }
  1769. $cond = array(
  1770. 'username' => $data['username'],
  1771. );
  1772. $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();
  1773. if(!$user_info){
  1774. json_fail('无登录权限或账号、密码错误');
  1775. }
  1776. if(!password_verify($data['password'], $user_info['password'])){
  1777. json_fail('账号或密码错误');
  1778. }
  1779. if($user_info['wx_open_id'] != $openid){
  1780. $update = array(
  1781. 'wx_open_id' => $openid,
  1782. 'last_login_ip' => $_SERVER['REMOTE_ADDR'],
  1783. 'last_login_time' => time(),
  1784. );
  1785. $result = M('users')->createSave(array('id'=>$user_info['uid']),$update);
  1786. if(!$result){
  1787. json_fail('登陆失败');
  1788. }
  1789. }
  1790. //如果当前openid与其他账号openid相同,清空其他表中openid
  1791. /*
  1792. $where = array(
  1793. 'wx_open_id' => $openid,
  1794. 'id' => ['NEQ', $user_info['id']],
  1795. );
  1796. $result = M('users')->createSave($where,['wx_open_id'=>'']);
  1797. if(!$result){
  1798. json_fail('登陆失败');
  1799. }
  1800. */
  1801. $res = array(
  1802. 'id'=>$user_info['uid'],
  1803. 'realname'=>$user_info['realname'],
  1804. 'avatar' => $user_info['avatar'],
  1805. 'phone'=>$user_info['phone'],
  1806. );
  1807. json_success('登录成功', $res);
  1808. }
  1809. public function getWaitHandleAlarmData( ){
  1810. header('Access-Control-Allow-Origin: *');
  1811. $post_data = json_decode(file_get_contents('php://input'), true);
  1812. $openid = $post_data['openid'];
  1813. $userid = $post_data['userid'];
  1814. //检测登录状态
  1815. $res = $this->checkLoginState($openid,$userid);
  1816. if(!$res['status']){
  1817. json_fail($res['message']);
  1818. }
  1819. // 获取登录账号部门下所有告警状态的学生数据
  1820. $user_model = M('users');
  1821. $where = ['id' => $userid];
  1822. $userinfo = $user_model->field('id,department_id')->where($where)->find();
  1823. // 获取权限范围内的用户id
  1824. $creator_ids = $this->getRightCreatorIds($userinfo);
  1825. if ($creator_ids === false) {
  1826. json_fail('获取数据失败');
  1827. }
  1828. $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
  1829. $page = isset($post_data['page']) ? $post_data['page'] : 1;
  1830. // 查出告警学生id
  1831. $cond = [
  1832. 'alarm_status' => 1,
  1833. ];
  1834. if (is_array($creator_ids)) {
  1835. $cond['creator_id'] = ['IN', $creator_ids];
  1836. }
  1837. // 查出总数量
  1838. $student_list = [];
  1839. $total = $user_model->where($cond)->count();
  1840. if ($total) {
  1841. $fields = 'id,avatar,realname,sex,age,active_rfid,student_no,online_time,last_station_mac,longitude,latitude';
  1842. $student_list = $user_model->field($fields)->where($cond)->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
  1843. }
  1844. // 返回
  1845. $data = [
  1846. 'total' => $total,
  1847. 'limit' => $limit,
  1848. 'page' => $page,
  1849. 'list' => $student_list,
  1850. ];
  1851. json_success('获取成功', $data);
  1852. }
  1853. private function getRightCreatorIds( $userinfo ){
  1854. $uid = $userinfo['id'];
  1855. $dept_id = $userinfo['department_id'];
  1856. // 非系统角色
  1857. $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']];
  1858. $devides_user_ids = M('roles')->where($where)->getField('id', true);
  1859. // 查出拥有系统角色
  1860. $where = [
  1861. 'uid' => $uid,
  1862. 'role_id' => ['NOT IN', $devides_user_ids],
  1863. ];
  1864. $role_ids = M('user_has_roles')->where($where)->getField('role_id', true);
  1865. if (empty($role_ids)) {
  1866. return false;
  1867. }
  1868. $user_ids = [];
  1869. $is_all = false; // 全部数据
  1870. // 查出角色拥有权限
  1871. $where = ['id' => ['IN', $role_ids]];
  1872. $range_list = M('roles')->distinct(true)->where($where)->getField('data_range', true);
  1873. if (empty($range_list)) {
  1874. return false;
  1875. }
  1876. // 根据角色权限查出
  1877. $depart_model = M('departments');
  1878. foreach($range_list as $range) {
  1879. switch ($range) {
  1880. case '1': // 全部数据
  1881. $is_all = true;
  1882. break;
  1883. case '2': // 自定义数据
  1884. case '3': // 本人数据
  1885. $user_ids[] = $uid;
  1886. break;
  1887. case '4': // 部门数据
  1888. $user_ids = array_merge($user_ids, $this->getUserIdsByDepartmentId([$dept_id]));
  1889. break;
  1890. case '5': // 部门及以下数据
  1891. // 查一下下级部门
  1892. // REGEXP '(^76$)|(^76-)'
  1893. //$departmentIds = $depart_model->where(['parent_id' => $dept_id])->getField('id', true);
  1894. $cond = ['level' => ['EXP',"REGEXP '(^{$dept_id}$)|(^{$dept_id}-)'"]];
  1895. $departmentIds = $depart_model->where($cond)->getField('id', true) ?: [];
  1896. $departmentIds[] = $dept_id;
  1897. $user_ids = array_merge([$uid], $this->getUserIdsByDepartmentId($departmentIds));
  1898. break;
  1899. default:
  1900. break;
  1901. }
  1902. // 如果有全部数据 直接跳出
  1903. if ($is_all) {
  1904. break;
  1905. }
  1906. }
  1907. if ($is_all) {
  1908. return true;
  1909. }
  1910. return array_unique(array_filter($user_ids));
  1911. }
  1912. private function getUserIdsByDepartmentId( $id ){
  1913. // 取出非设备用户 (roles identify not in 'personal,group_badge_user,group_card_user')
  1914. $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']];
  1915. $devide_role_ids = M('roles')->where($where)->getField('id', true);
  1916. $devide_role_ids = join(',', $devide_role_ids);
  1917. $cond = [
  1918. 'u.department_id' => ['IN', $id],
  1919. ];
  1920. $ids = M('users')->alias('u')
  1921. ->field('u.id')
  1922. ->where($cond)
  1923. ->join("INNER JOIN user_has_roles r ON u.id=r.uid AND r.role_id NOT IN ({$devide_role_ids})")
  1924. ->select() ? : [];
  1925. return array_unique(array_column($ids, 'id'));
  1926. }
  1927. public function getConfirmAlarmData( ){
  1928. header('Access-Control-Allow-Origin: *');
  1929. $post_data = json_decode(file_get_contents('php://input'), true);
  1930. $openid = $post_data['openid'];
  1931. if(!$openid){
  1932. json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
  1933. }
  1934. $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
  1935. $page = isset($post_data['page']) ? $post_data['page'] : 1;
  1936. // 获取登录账号部门下所有告警状态的学生数据
  1937. $where = ['wx_open_id' => $openid];
  1938. $userinfo = M('users')->field('id,department_id')->where($where)->find();
  1939. // 获取权限范围内的用户id
  1940. $creator_ids = $this->getRightCreatorIds($userinfo);
  1941. if ($creator_ids === false) {
  1942. json_fail('获取失败');
  1943. }
  1944. // 查出告警学生id
  1945. $cond = [
  1946. 'result' => 1,
  1947. ];
  1948. if (is_array($creator_ids)) {
  1949. $cond['creator_id'] = ['IN', $creator_ids];
  1950. }
  1951. // 查出总数量
  1952. $record_list = [];
  1953. $alarm_handle_records_model = M('alarm_handle_records');
  1954. $total = $alarm_handle_records_model->where($cond)->count();
  1955. if ($total) {
  1956. $record_list = $alarm_handle_records_model->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
  1957. }
  1958. // 返回
  1959. $data = [
  1960. 'total' => $total,
  1961. 'limit' => $limit,
  1962. 'page' => $page,
  1963. 'list' => $record_list,
  1964. ];
  1965. json_success('获取成功', $data);
  1966. }
  1967. public function getCancelAlarmData( ){
  1968. header('Access-Control-Allow-Origin: *');
  1969. $post_data = json_decode(file_get_contents('php://input'), true);
  1970. $openid = $post_data['openid'];
  1971. if(!$openid){
  1972. json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
  1973. }
  1974. $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
  1975. $page = isset($post_data['page']) ? $post_data['page'] : 1;
  1976. // 获取登录账号部门下所有告警状态的学生数据
  1977. $where = ['wx_open_id' => $openid];
  1978. $userinfo = M('users')->field('id,department_id')->where($where)->find();
  1979. // 获取权限范围内的用户id
  1980. $creator_ids = $this->getRightCreatorIds($userinfo);
  1981. if ($creator_ids === false) {
  1982. json_fail('获取失败');
  1983. }
  1984. // 查出告警学生id
  1985. $cond = [
  1986. 'result' => 2,
  1987. ];
  1988. if (is_array($creator_ids)) {
  1989. $cond['creator_id'] = ['IN', $creator_ids];
  1990. }
  1991. // 查出总数量
  1992. $record_list = [];
  1993. $alarm_handle_records_model = M('alarm_handle_records');
  1994. $total = $alarm_handle_records_model->where($cond)->count();
  1995. if ($total) {
  1996. $record_list = $alarm_handle_records_model->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
  1997. }
  1998. // 返回
  1999. $data = [
  2000. 'total' => $total,
  2001. 'limit' => $limit,
  2002. 'page' => $page,
  2003. 'list' => $record_list,
  2004. ];
  2005. json_success('获取成功', $data);
  2006. }
  2007. public function getFenceAlarmData( ){
  2008. header('Access-Control-Allow-Origin: *');
  2009. $post_data = json_decode(file_get_contents('php://input'), true);
  2010. $openid = $post_data['openid'];
  2011. if(!$openid){
  2012. json_fail('未获取到微信授权信息,请重新点击菜单进入并授权');
  2013. }
  2014. $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
  2015. $page = isset($post_data['page']) ? $post_data['page'] : 1;
  2016. // 获取登录账号部门下所有告警状态的学生数据
  2017. $where = ['wx_open_id' => $openid];
  2018. $userinfo = M('users')->field('id,department_id')->where($where)->find();
  2019. // 获取权限范围内的用户id
  2020. $creator_ids = $this->getRightCreatorIds($userinfo);
  2021. if ($creator_ids === false) {
  2022. json_fail('获取失败');
  2023. }
  2024. // 查出围栏
  2025. $cond = [];
  2026. if (!$post_data['type']) {
  2027. $cond['alarm_type'] = ['IN',['fence_in','fence_out']];
  2028. } elseif ($post_data['type'] == 'in') {
  2029. $cond['alarm_type'] = 'fence_in';
  2030. } elseif ($post_data['type'] == 'out') {
  2031. $cond['alarm_type'] = 'fence_out';
  2032. } else {
  2033. json_fail('未知的围栏类型');
  2034. }
  2035. if (is_array($creator_ids)) {
  2036. $cond['creator_id'] = ['IN', $creator_ids];
  2037. }
  2038. // 查出总数量
  2039. $list = [];
  2040. $alarm_report = M('alarm_report');
  2041. $total = $alarm_report->where($cond)->count();
  2042. if ($total) {
  2043. $list = $alarm_report->where($cond)->order('created_at desc')->limit($post_data['limit'])->page($post_data['page'])->select() ?: [];
  2044. }
  2045. // 返回
  2046. $data = [
  2047. 'total' => $total,
  2048. 'limit' => $limit,
  2049. 'page' => $page,
  2050. 'list' => $list,
  2051. ];
  2052. json_success('获取成功', $data);
  2053. }
  2054. public function getYysFences( ){
  2055. // 获取登录用户信息
  2056. $userinfo = $this->getYysLoginUserinfo();
  2057. // 获取权限范围内的用户id
  2058. $creator_ids = $this->getRightCreatorIds($userinfo);
  2059. if ($creator_ids === false) {
  2060. json_fail('获取失败');
  2061. }
  2062. $fence_type = I('get.type');
  2063. if (!$fence_type && $fence_type !== 0 && $fence_type !== '0') {
  2064. json_fail('未获取到围栏类型');
  2065. }
  2066. $cond = [
  2067. 'fence_type' => $fence_type,
  2068. ];
  2069. // 查出总数量
  2070. if (is_array($creator_ids)) {
  2071. $cond['creator_id'] = ['IN', $creator_ids];
  2072. }
  2073. $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';
  2074. $list = M('fences')->field($field)->where($cond)->select();
  2075. if(!$list){
  2076. json_fail('暂无围栏');
  2077. }
  2078. $geometry = new \Jms\Algo\Geometry();
  2079. foreach($list as &$v){
  2080. $v['inAlarm'] = (bool)($v['inAlarm']);
  2081. $v['outAlarm'] = (bool)($v['outAlarm']);
  2082. // 坐标转换:GCJ-02 -> BD-09
  2083. $v['fenceInfo'] = json_decode($v['fenceInfo'], true) ?:[];
  2084. $convPoint = $geometry->convertBd09ToGcj02($v['fenceInfo']['center']['lat'], $v['fenceInfo']['center']['lng']);
  2085. $v['fenceInfo']['center']['lat'] = $convPoint['lat'];
  2086. $v['fenceInfo']['center']['lng'] = $convPoint['lng'];
  2087. }
  2088. json_success('获取成功', $list);
  2089. }
  2090. private function getRecSignature( $url ){
  2091. header('Access-Control-Allow-Origin: *');
  2092. $url = urldecode($url);
  2093. $accessToken = $this->getWeixinAccessToken();
  2094. if (!$accessToken) {
  2095. return [
  2096. 'c' => 99,
  2097. 'm' => '获取微信accesstoken失败'
  2098. ];
  2099. }
  2100. $apiTiket = $this->getJsapiTikcet($accessToken);
  2101. if(is_array($apiTiket)){
  2102. json_fail($apiTiket['errcode'].':'.$apiTiket['errmsg']);
  2103. return [
  2104. 'c' => $apiTiket['errcode'],
  2105. 'm' => $apiTiket['errmsg']
  2106. ];
  2107. }
  2108. $noncestr = substr(md5(time()), 0, 16);
  2109. $timestamp = time();
  2110. //jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value
  2111. $str = 'jsapi_ticket='.$apiTiket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
  2112. $signature = sha1($str);
  2113. return [
  2114. 'c' => 0,
  2115. 'm' => '',
  2116. 'v' => [
  2117. 'appid' => C('WECHAT_APPID'),
  2118. 'timestamp' => $timestamp,
  2119. 'noncestr' => $noncestr,
  2120. 'signature' => $signature,
  2121. ]
  2122. ];
  2123. }
  2124. public function addEditFence( ){
  2125. // 获取登录用户信息
  2126. $userinfo = $this->getYysLoginUserinfo();
  2127. $id = I('get.id');
  2128. $data = json_decode( file_get_contents("php://input") ,true) ?: [];
  2129. // 围栏类型
  2130. $fenceTypeArr = [
  2131. 'inout' => 0, // 机构安全围栏
  2132. 'person_inout' => 1, // 个人安全围栏
  2133. 'sos' => 2, // SOS围栏
  2134. ];
  2135. if ($data['name']) {
  2136. $data['name'] = trim($data['name']);
  2137. }
  2138. if ($data['fence_info']) {
  2139. // 坐标转换:GCJ-02 -> BD-09
  2140. $convPoint = (new \Jms\Algo\Geometry())->convertGcj02ToBd09($data['fence_info']['center']['lat'], $data['fence_info']['center']['lng']);
  2141. $data['fence_info']['center']['lat'] = $convPoint['lat'];
  2142. $data['fence_info']['center']['lng'] = $convPoint['lng'];
  2143. $data['fence_info'] = json_encode($data['fence_info']);
  2144. }
  2145. if ($data['in_fence_time_area'] && is_array($data['in_fence_time_area'])) {
  2146. $data['in_fence_time_area'] = json_encode($data['in_fence_time_area']);
  2147. }
  2148. if ($data['out_fence_time_area'] && is_array($data['out_fence_time_area'])) {
  2149. $data['out_fence_time_area'] = json_encode($data['out_fence_time_area']);
  2150. }
  2151. if ($data['push_users'] && is_array($data['push_users'])) {
  2152. foreach($data['push_users'] as &$v){
  2153. $v = intval($v);
  2154. }
  2155. $data['push_users'] = json_encode($data['push_users']);
  2156. }
  2157. // 新增
  2158. if (!$id) {
  2159. if($data['name'] === ''){
  2160. json_fail('围栏名称不能为空');
  2161. }
  2162. if(!$data['fence_info']){
  2163. json_fail('未获取到围栏信息');
  2164. }
  2165. if (!isset($fenceTypeArr[$data['fence_type']])) {
  2166. json_fail('未知的围栏类型');
  2167. }
  2168. $data['fence_shape'] = $data['fence_shape'] ?: 'circle';
  2169. $data['fence_type'] = $fenceTypeArr[$data['fence_type']];
  2170. $data['creator_id'] = $userinfo['id'];
  2171. $data['departments'] = $userinfo['department_id'];
  2172. $data['created_at'] = time();
  2173. $result = M('fences')->createAdd($data);
  2174. if (!$result) {
  2175. json_fail('添加失败');
  2176. }
  2177. json_success('添加成功', $result);
  2178. }
  2179. // 修改
  2180. // 获取权限范围内的用户id
  2181. $creatorIds = $this->getRightCreatorIds($userinfo);
  2182. $info = M('fences')->where(['id'=>$id])->find();
  2183. if (empty($info)) {
  2184. json_fail('获取围栏信息失败');
  2185. }
  2186. if (!in_array($info['creator_id'], $creatorIds)) {
  2187. //json_fail('无修改权限');
  2188. }
  2189. unset($data['fence_type']);
  2190. $cond = ['id'=>$id];
  2191. $result = M('fences')->createSave($cond, $data);
  2192. if(!$result){
  2193. json_fail('保存失败');
  2194. }
  2195. json_success('保存成功', $id);
  2196. }
  2197. public function deleteYysFences( ){
  2198. // 获取登录用户信息
  2199. $userinfo = $this->getYysLoginUserinfo();
  2200. // 获取权限范围内的用户id
  2201. $creator_ids = $this->getRightCreatorIds($userinfo);
  2202. if ($creator_ids === false) {
  2203. json_fail('获取失败');
  2204. }
  2205. $id = I('get.id');
  2206. if (!$id) {
  2207. json_fail('参数不合法');
  2208. }
  2209. $fence_info = M('fences')->where(['id'=>$id])->find();
  2210. if (!$fence_info) {
  2211. json_fail('围栏不存在');
  2212. }
  2213. if ($creator_ids !== true && !in_array($fence_info['creator_id'], $creator_ids)) {
  2214. json_fail('无权限删除该围栏');
  2215. }
  2216. $res = M('fences')->where(['id'=>$id])->delete();
  2217. if (!$res) {
  2218. json_fail('删除失败');
  2219. }
  2220. json_success('删除成功');
  2221. }
  2222. public function getFenceInfo( ){
  2223. // 获取登录用户信息
  2224. $userinfo = $this->getYysLoginUserinfo();
  2225. $id = I('get.id');
  2226. if (!$id) {
  2227. json_fail('缺少参数');
  2228. }
  2229. $info = M('fences')->where(['id'=>$id])->find();
  2230. if(!$info){
  2231. json_fail('获取失败');
  2232. }
  2233. // GCJ-02 -> BD-09
  2234. $info['fence_info'] = json_decode($info['fence_info'], true) ?: [];
  2235. $convPoint = (new \Jms\Algo\Geometry())->convertBd09ToGcj02($info['fence_info']['center']['lat'], $info['fence_info']['center']['lng']);
  2236. $info['fence_info']['center']['lat'] = $convPoint['lat'];
  2237. $info['fence_info']['center']['lng'] = $convPoint['lng'];
  2238. $info['in_fence_time_area'] = json_decode($info['in_fence_time_area'], true) ?: [];
  2239. $info['out_fence_time_area'] = json_decode($info['out_fence_time_area'], true) ?: [];
  2240. $info['push_users'] = json_decode($info['push_users'], true) ?: [];
  2241. json_success('获取成功', $info);
  2242. }
  2243. public function getFenceAlarmIntervals( ){
  2244. header('Access-Control-Allow-Origin: *');
  2245. $userid = I('get.userid');
  2246. $openid = I('get.openid');
  2247. if(!$userid || $userid == 'undefined' || $userid == 'null'){
  2248. json_fail('未获取到用户标识,请重新登陆');
  2249. }
  2250. //检测登录状态
  2251. $res = $this->checkLoginState($openid, $userid);
  2252. if(!$res['status']){
  2253. json_fail($res['message']);
  2254. }
  2255. try {
  2256. $typeid = M('sys_dict_type')->where(['code'=>'FenceSentInterval'])->getField('id');
  2257. $list = M('sys_dict_data')->field('value as text,code as value')->where(['type_id'=>$typeid])->select() ? : [];
  2258. } catch (\Exception $e) {
  2259. json_fail($e->getMessage());
  2260. }
  2261. json_success('获取成功', $list);
  2262. }
  2263. public function getRightUsers( ){
  2264. // 获取登录用户信息
  2265. $userinfo = $this->getYysLoginUserinfo();
  2266. // 获取权限范围内的用户id
  2267. $creator_ids = $this->getRightCreatorIds($userinfo);
  2268. if ($creator_ids === false) {
  2269. json_fail('获取失败');
  2270. }
  2271. $cond = [
  2272. 'username' => ['NOT IN', 'admin,manage']
  2273. ];
  2274. if (is_array($creator_ids)) {
  2275. $cond['id'] = ['IN', $creator_ids];
  2276. }
  2277. if ($creator_ids === true) {
  2278. $where = ['identify' => ['IN', 'personal,group_badge_user,group_card_user']];
  2279. $devide_user_ids = M('roles')->where($where)->getField('id', true);
  2280. $device_ids = join(',', $devide_user_ids);
  2281. $list = M('users')->alias('u')->field('u.id,u.realname,u.phone')
  2282. ->where($cond)
  2283. ->distinct(true)
  2284. ->join("INNER JOIN user_has_roles r ON u.id=r.uid AND r.role_id NOT IN ({$device_ids})")
  2285. ->select() ?:[];
  2286. } else {
  2287. $list = M('users')->field('id,realname,phone')->distinct(true)->where($cond)->select();
  2288. }
  2289. json_success('获取成功', $list);
  2290. }
  2291. public function getUserAlarmRecords( ){
  2292. header('Access-Control-Allow-Origin: *');
  2293. $post_data = json_decode(file_get_contents('php://input'), true);
  2294. $openid = $post_data['openid'];
  2295. $userid = $post_data['userid'];
  2296. //检测登录状态
  2297. $res = $this->checkLoginState($openid,$userid);
  2298. if(!$res['status']){
  2299. json_fail($res['message']);
  2300. }
  2301. $limit = isset($post_data['limit']) ? $post_data['limit'] : 10;
  2302. $page = isset($post_data['page']) ? $post_data['page'] : 1;
  2303. // 告警记录条件
  2304. $where = ['user_id' => $userid];
  2305. $device_numbers = M('devices')->where($where)->getField('imei', true);
  2306. if (empty($device_numbers)) {
  2307. json_fail('暂无设备,请先绑定设备');
  2308. }
  2309. // 初始化条件
  2310. $cond = [
  2311. 'device_number' => ['IN', $device_numbers],
  2312. ];
  2313. $reason = I('get.reason');
  2314. $state = I('get.state');
  2315. $result = I('get.result');
  2316. if ($reason) {
  2317. if ($reason == 'fence') {
  2318. $cond['alarm_reason'] = ['IN', ['fence_in', 'fence_out']];
  2319. } else {
  2320. $cond['alarm_reason'] = $reason;
  2321. }
  2322. } else {
  2323. // 默认只显示 SOS
  2324. $cond['alarm_reason'] = 'press';
  2325. }
  2326. if ($state) {
  2327. $cond['state'] = $state;
  2328. }
  2329. if ($result !== '' && is_numeric($result)) {
  2330. $cond['result'] = $result;
  2331. }
  2332. // 查出总数量
  2333. $list = [];
  2334. $total = M('alarm_records')->where($cond)->count();
  2335. if ($total) {
  2336. if ($state == 'start' || $state == 'end') {
  2337. $order = "{$state}_time desc";
  2338. } else {
  2339. $order = 'id desc';
  2340. }
  2341. $fields = 'id,device_number,alarm_reason,handler_id,start_time,end_time,state,comment,result';
  2342. $list = M('alarm_records')->field($fields)->where($cond)->limit($limit)->page($page)->order($order)->select() ?: [];
  2343. if (!empty($list)) {
  2344. // alarm_reason,handler_id,result
  2345. // 获取告警类型
  2346. $typeid = M('sys_dict_type')->where(['code' => 'AlarmType'])->getField('id');
  2347. $reason_arr = M('sys_dict_data')->where(['type_id' => $typeid])->getField('code, value');
  2348. // 处理结果
  2349. $result_arr = [
  2350. 0 => '待处理',
  2351. 1 => '已处理',
  2352. 2 => '误报',
  2353. ];
  2354. // 中文转换
  2355. foreach ($list as &$alarm) {
  2356. $alarm['start_time'] = $alarm['start_time'] ? date('Y-m-d H:i:s', $alarm['start_time']) : '';
  2357. $alarm['end_time'] = $alarm['end_time'] ? date('Y-m-d H:i:s', $alarm['end_time']) : '';
  2358. if (is_array($reason_arr)) {
  2359. $alarm['alarm_reason'] = $reason_arr[$alarm['alarm_reason']];
  2360. }
  2361. if (is_numeric($alarm['result'])) {
  2362. $alarm['result'] = $result_arr[$alarm['result']];
  2363. }
  2364. }
  2365. }
  2366. }
  2367. // 返回
  2368. $data = [
  2369. 'total' => $total,
  2370. 'limit' => $limit,
  2371. 'page' => $page,
  2372. 'list' => $list,
  2373. ];
  2374. json_success('获取成功', $data);
  2375. }
  2376. public function getUserAlarmDetail( ){
  2377. header('Access-Control-Allow-Origin: *');
  2378. $openid = I('get.openid');
  2379. $userid = I('get.userid');
  2380. if(!$userid || $userid == 'undefined' || $userid == 'null'){
  2381. json_fail('获取不到你的用户标识,请重新登陆');
  2382. }
  2383. //检测登录状态
  2384. $res = $this->checkLoginState($openid,$userid);
  2385. if(!$res['status']){
  2386. json_fail($res['message']);
  2387. }
  2388. $alarm_id = I('get.id');
  2389. if (!$alarm_id) {
  2390. json_fail('获取告警信息失败1');
  2391. }
  2392. // 查出告警数据
  2393. $where = ['id' => $alarm_id];
  2394. $alarm_info = M('alarm_records')->where($where)->find();
  2395. if (empty($alarm_info)) {
  2396. json_fail('获取告警信息失败2');
  2397. }
  2398. $report_id = I('get.rid');
  2399. if (!$report_id) {
  2400. json_fail('获取告警信息失败3');
  2401. }
  2402. $where = ['id' => $report_id];
  2403. $alarm_report = M('alarm_report')->where($where)->find();
  2404. if (empty($alarm_report)) {
  2405. json_fail('获取告警信息失败4');
  2406. }
  2407. $alarm_info['address']=$alarm_report['address'];
  2408. // 查出设备信息
  2409. $where = ['imei' => $alarm_info['device_number']];
  2410. $device_info = M('devices')->where($where)->find();
  2411. if (empty($alarm_info)) {
  2412. json_fail('获取告警设备信息失败');
  2413. }
  2414. if ($device_info['online_time'] > $device_info['wifi_online_time']) {
  2415. $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['online_time']);
  2416. $device_info['last_location'] = $device_info['longitude'] .','. $device_info['latitude'];
  2417. $res = bmap_geocoding($device_info['latitude'], $device_info['longitude']);
  2418. if($res['success']){
  2419. $device_info['address'] = $res['address'];
  2420. }else{
  2421. $device_info['address']='';
  2422. }
  2423. } elseif ($device_info['online_time'] < $device_info['wifi_online_time']) {
  2424. $device_info['last_online_time'] = date('Y-m-d H:i:s', $device_info['wifi_online_time']);
  2425. $device_info['last_location'] = $device_info['wifi_longitude'] .','. $device_info['wifi_latitude'];
  2426. } else {
  2427. $device_info['last_online_time'] = '0000-00-00 00:00:00';
  2428. $device_info['last_location'] = '';
  2429. $device_info['address']='';
  2430. }
  2431. // 查出设备用户
  2432. if ($device_info['badge_user_id']) {
  2433. $where = ['id' => $device_info['badge_user_id']];
  2434. $user_info = M('badgeuser')->where($where)->find() ?: [];
  2435. } else {
  2436. $where = ['id' => $device_info['user_id']];
  2437. $user_info = M('users')->where($where)->find() ?: [];
  2438. }
  2439. //if (empty($user_info)) {
  2440. //json_fail('获取告警用户信息失败');
  2441. //}
  2442. // 获取紧急联系人
  2443. $where = ['device_id' => $device_info['id']];
  2444. $urgent_list = M('kq_urgent')->where($where)->select() ? : [];
  2445. if (!empty($urgent_list)) {
  2446. $type_id = M('sys_dict_type')->where(['code' => 'Relationships'])->getField('id');
  2447. $ships = M('sys_dict_data')->where(['type_id' => $type_id])->getField('code,value');
  2448. foreach ($urgent_list as $key => &$urgent) {
  2449. $urgent['relationship_text'] = $ships[$urgent['relationship']];
  2450. }
  2451. }
  2452. // 部门名称
  2453. $alarm_info['department_name'] = M('departments')->where(['id' => $user_info['department_id']])->getField('department_name');
  2454. $alarm_info['user_info'] = $user_info;
  2455. $alarm_info['urgent_list'] = $urgent_list;
  2456. $alarm_info['device_info'] = $device_info;
  2457. $alarm_info['device_info']['department_name'] = $alarm_info['department_name'];
  2458. json_success('获取成功', $alarm_info);
  2459. }
  2460. public function setFenceAlarmInterval( ){
  2461. //user_has_students
  2462. header('Access-Control-Allow-Origin: *');
  2463. $fenceId = I('get.fenceId');
  2464. $interval = intval(I('get.interval') );
  2465. if(!$fenceId){
  2466. json_fail('获取不到围栏标识,请刷新下');
  2467. }
  2468. if(!$interval){
  2469. json_fail('获取不到时间间隔,请重设重试');
  2470. }
  2471. if($interval < 1 || $interval > 720){
  2472. json_fail('推送间隔目前只支持720分钟以内');
  2473. }
  2474. $saveData = [
  2475. 'sent_interval' => $interval
  2476. ];
  2477. $saveData['sent_interval'] = $interval * 60;
  2478. $res = M('fences')->where(['id' => $fenceId])->save($saveData);
  2479. if($res === false){
  2480. json_fail('修改推送间隔失败');
  2481. }
  2482. json_success('修改推送间隔成功');
  2483. }
  2484. public function resetPwd( ){
  2485. header('Access-Control-Allow-Origin: *');
  2486. // 通过手机号和短信验证码注册
  2487. $data = json_decode( file_get_contents("php://input") ,true);
  2488. // 用户类型:个人(personal)、团体(group)
  2489. $userType = $data['userType'];
  2490. // 设备类型:卡牌(card)、徽章(badge)
  2491. $deviceType = $data['deviceType'];
  2492. // 团体卡牌用户(group_card_user) 不可注册
  2493. // 个人用户(personal),团体徽章用户(group_badge_user) 可注册
  2494. if ($userType == 'personal') { // 个人用户
  2495. $identify = 'personal';
  2496. } elseif ($userType == 'group' && $deviceType == 'badge') { // 团体徽章用户
  2497. $identify = 'group_badge_user';
  2498. } elseif ($userType == 'group' && $deviceType == 'card') { // 团体卡牌用户
  2499. $identify = 'group_card_user';
  2500. } else {
  2501. json_fail('未知用户类型');
  2502. }
  2503. if(!$data['phone']){
  2504. json_fail('手机号码不能为空');
  2505. }
  2506. if(!$data['smsCode']){
  2507. json_fail('短信验证码不能为空');
  2508. }
  2509. if(! $data['password']){
  2510. json_fail('密码不能为空');
  2511. }
  2512. if(! $data['confirmPassword']){
  2513. json_fail('确认密码不能为空');
  2514. }
  2515. if ($data['password'] != $data['confirmPassword']) {
  2516. json_fail('两次密码不一致');
  2517. }
  2518. // 获取角色id
  2519. $roleId = M('roles')->where(['identify' => $identify])->getField('id');
  2520. if (!$roleId) {
  2521. json_fail('未知角色类型');
  2522. }
  2523. // 判断角色、号码是否已注册
  2524. $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();
  2525. if (empty($userinfo)) {
  2526. json_fail('该号码未注册');
  2527. }
  2528. // 验证码有效性
  2529. $res = $this->isValidSmsCode($data['phone'], $data['smsCode']);
  2530. if (!$res['success']) {
  2531. json_fail($res['message']);
  2532. }
  2533. // 重置密码
  2534. $savePwd = password_hash($data['password'], PASSWORD_DEFAULT);
  2535. $cond = ['id' => $userinfo['id']];
  2536. $res = M('users')->where($cond)->setField('password', $savePwd);
  2537. if($res === false){
  2538. json_fail('重置失败');
  2539. }
  2540. json_success('重置成功');
  2541. }
  2542. public function checkSingleLogin( ){
  2543. header('Access-Control-Allow-Origin: *');
  2544. $userid = I('get.userid');
  2545. $openid = I('get.openid');
  2546. $where = [
  2547. 'id' => $userid,
  2548. 'wx_open_id'=> $openid
  2549. ];
  2550. $flag = M('users')->where($where)->find();
  2551. if($flag){
  2552. json_success('goon');
  2553. }
  2554. json_fail('relogin');
  2555. }
  2556. private function getMaxDbm( $avFile, $start ){
  2557. /*
  2558. $string = file_get_contents($avFile);
  2559. $bytes = array();
  2560. for($i = 0; $i < strlen($string); $i++){
  2561. $bytes[] = ord($string[$i]);
  2562. }
  2563. $counter = strlen($string);
  2564. */
  2565. $counter = 4;
  2566. $bytes = [1,2,3,4];
  2567. $absolute = 0;
  2568. $maximum = 0;
  2569. for ($i = $start; $i < $counter; $i++) {
  2570. // $absolute = abs(getShort(new byte[] {vector[i], vector[i + 1]}, 0));
  2571. $absolute = abs( $this->bytesToShort([$bytes[$i], $bytes[$i+1]], 0) ) ;
  2572. if ($absolute > $maximum) {
  2573. $maximum = $absolute;
  2574. }
  2575. $i++;
  2576. }
  2577. if ($maximum > 32767) {
  2578. $maximum = 32767;
  2579. }
  2580. return (int)$maximum;
  2581. }
  2582. public function test_cus_function( ){
  2583. $accessKeyId='LTAIOSQ4y09Jxbf3';
  2584. $accessKeySecret='LQm05sOLBss87lFG6jx9iq4lzKCAqA';
  2585. $config = new \Darabonba\OpenApi\Models\Config([
  2586. "accessKeyId" => $accessKeyId,
  2587. "accessKeySecret" => $accessKeySecret
  2588. ]);
  2589. // 访问的域名
  2590. $config->endpoint = "dysmsapi.aliyuncs.com";
  2591. $client= new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);
  2592. $params = [
  2593. "signName" => "小友回收",
  2594. "templateCode" => "SMS_245515027",
  2595. "phoneNumbers" => 15706857065,
  2596. "templateParam" => json_encode(['code' => '1234'])
  2597. ];
  2598. // $client = self::createClient( $accessKeyId, $accessKeySecret);
  2599. $sendSmsRequest = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest($params);
  2600. $runtime = new \AlibabaCloud\Tea\Utils\Utils\RuntimeOptions([]);
  2601. $res=$client->sendSmsWithOptions($sendSmsRequest, $runtime);
  2602. var_dump($res);
  2603. }
  2604. private function bytesToShort( $bytes, $position ){
  2605. $val = 0;
  2606. $val = $bytes[$position + 1] & 0xFF;
  2607. $val = $val << 8;
  2608. $val |= $bytes[$position] & 0xFF;
  2609. return $val;
  2610. }
  2611. public function getDeviceAvatar( ){
  2612. header('Access-Control-Allow-Origin: *');
  2613. $imei = I('get.imei');
  2614. if(!$imei){
  2615. json_fail('获取不到设备标识');
  2616. }
  2617. $avatar = M('devices')->where(['imei' => $imei])->getField('avatar');
  2618. if(!$avatar){
  2619. json_fail('获取头像失败');
  2620. }
  2621. json_success('获取头像成功',$avatar);
  2622. }
  2623. public function getUserAvatar( ){
  2624. header('Access-Control-Allow-Origin: *');
  2625. $uid = I('get.uid');
  2626. if(!$uid){
  2627. json_fail('获取不到用户标识');
  2628. }
  2629. $avatar = M('users')->where(['id' => $uid])->getField('avatar');
  2630. if(!$avatar){
  2631. json_fail('获取头像失败');
  2632. }
  2633. json_success('获取头像成功',$avatar);
  2634. }
  2635. public function saveDeviceAvatar( ){
  2636. header('Access-Control-Allow-Origin: *');
  2637. $postData = json_decode( file_get_contents('php://input'), true);
  2638. if(!$postData['imei']){
  2639. json_fail('获取不到设备标识');
  2640. }
  2641. if(!$postData['avatar64content']){
  2642. json_fail('获取不到头像信息');
  2643. }
  2644. $folder = realpath(__ROOT__).'/static/assets/avatar/'.date('Ymd').'/';
  2645. if (!is_dir($folder)){
  2646. $mres= mkdir($folder,0777,true);
  2647. if($mres === false){
  2648. json_fail('服务端创建目录权限不足');
  2649. }
  2650. }
  2651. $fileName = 'avatar-device-imei'.$postData['imei'] .'-'. time();
  2652. $saveFile = $this->base64_image_content($postData['avatar64content'], $folder, $fileName);
  2653. if(!$saveFile){
  2654. json_fail('服务端保存头像失败');
  2655. }
  2656. $res = M('devices')->where(['imei' => $postData['imei']])->save(['avatar' => $saveFile]);
  2657. if($res === false){
  2658. json_fail('保存头像地址失败');
  2659. }
  2660. json_success('保存成功');
  2661. }
  2662. public function saveUserAvatar( ){
  2663. header('Access-Control-Allow-Origin: *');
  2664. $postData = json_decode( file_get_contents('php://input'), true);
  2665. if(!$postData['uid']){
  2666. json_fail('获取不到用户标识');
  2667. }
  2668. if(!$postData['avatar64content']){
  2669. json_fail('获取不到头像信息');
  2670. }
  2671. $folder = realpath(__ROOT__).'/static/assets/avatar/'.date('Ymd').'/';
  2672. if (!is_dir($folder)){
  2673. $mres= mkdir($folder,0777,true);
  2674. if($mres === false){
  2675. json_fail('服务端创建目录权限不足');
  2676. }
  2677. }
  2678. $fileName = 'avatar-user-uid'.$postData['uid'] .'-'. time();
  2679. $saveFile = $this->base64_image_content($postData['avatar64content'], $folder, $fileName);
  2680. if(!$saveFile){
  2681. json_fail('服务端保存头像失败');
  2682. }
  2683. $res = M('users')->where(['id' => $postData['uid']])->save(['avatar' => $saveFile]);
  2684. if($res === false){
  2685. json_fail('保存头像地址失败');
  2686. }
  2687. json_success('保存成功');
  2688. }
  2689. private function base64_image_content( $base64_image_content, $path, $name ){
  2690. //匹配出图片的格式
  2691. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
  2692. $type = $result[2];
  2693. $new_file = $path.$name.".{$type}";
  2694. $file = 'http://'.$_SERVER['HTTP_HOST'].'/static/assets/avatar/'.date('Ymd').'/'.$name.".{$type}";
  2695. if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
  2696. return $file;
  2697. }else{
  2698. return false;
  2699. }
  2700. }else{
  2701. return false;
  2702. }
  2703. }
  2704. public function setLocModel( ){
  2705. /*
  2706. 请求url上带上 openid userid
  2707. post请求 参数: imei id(设备id) post_mode 定位模式 0-常规模式 1-追踪模式 2-定时模式
  2708. 定时模式:需要设置 定位采样间隔(stopped_rtc_invl) 定位上报间隔(stopped_rpt_invl)
  2709. */
  2710. header('Access-Control-Allow-Origin: *');
  2711. $openid = I('get.openid');
  2712. $userid = I('get.userid');
  2713. //检测登录状态
  2714. $res=$this->checkLoginState($openid,$userid);
  2715. if(!$res['status']){
  2716. json_fail($res['message']);
  2717. }
  2718. $data = json_decode( file_get_contents("php://input") ,true);
  2719. $imei=$data['imei'];
  2720. if(!$imei){
  2721. json_fail('缺少设备imei号');
  2722. }
  2723. $config['pos_mode']=$data['pos_mode'];
  2724. if(!isset($config['pos_mode']) || $config['pos_mode'] === ''){
  2725. json_fail('缺少定位模式');
  2726. }
  2727. $dev_id=$data['id'];
  2728. if(!$dev_id){
  2729. json_fail('缺少设备id');
  2730. }
  2731. $redis = Redis('c61_gps_device_configs_'.$imei,"queue");
  2732. //开启事务
  2733. M()->startTrans();
  2734. $config['msg_id'] = 0xAAAA0010;
  2735. //判断是不是定时模式
  2736. if ($config['pos_mode'] == 2) {
  2737. if(!$data['stopped_rtc_invl']){
  2738. json_fail('请设置定位采样间隔');
  2739. }
  2740. if(!$data['stopped_rpt_invl']){
  2741. json_fail('请设置定位上报间隔');
  2742. }
  2743. $config_arr = array(
  2744. 'stopped_rtc_invl' => intval($data['stopped_rtc_invl']),
  2745. 'stopped_rpt_invl' => intval($data['stopped_rpt_invl']),
  2746. 'msg_id' => 0xAAAA0007
  2747. );
  2748. //下发日志
  2749. $log_data = array(
  2750. 'send_contents' => json_encode($config_arr),
  2751. 'type'=>'sensor',
  2752. 'imei'=>$imei,
  2753. 'created_at' => time(),
  2754. 'creator_id' => $userid,
  2755. 'device_id' => $dev_id
  2756. );
  2757. $lg_id = M('send_config_log')->createAdd($log_data);
  2758. if (!$lg_id) {
  2759. json_fail('下发日志添加失败');
  2760. M()->rollback();
  2761. }
  2762. $config_arr['id'] = $lg_id;
  2763. $redis->push(json_encode($config_arr));
  2764. }else{//非定时模式 采样时间设为3000 上报间隔3600
  2765. $config_arr = array(
  2766. 'stopped_rtc_invl' => 3000,
  2767. 'stopped_rpt_invl' => 3600,
  2768. 'msg_id' => 0xAAAA0007
  2769. );
  2770. //下发日志
  2771. $log_data = array(
  2772. 'send_contents' => json_encode($config_arr),
  2773. 'type'=>'sensor',
  2774. 'imei'=>$imei,
  2775. 'created_at' => time(),
  2776. 'creator_id' => $userid,
  2777. 'device_id' => $dev_id
  2778. );
  2779. $lg_id = M('send_config_log')->createAdd($log_data);
  2780. if (!$lg_id) {
  2781. json_fail('下发日志添加失败');
  2782. M()->rollback();
  2783. }
  2784. $config_arr['id'] = $lg_id;
  2785. $redis->push(json_encode($config_arr));
  2786. }
  2787. //下发日志
  2788. $log_data = array(
  2789. 'send_contents' => json_encode($config),
  2790. 'type'=>'pos_mode',
  2791. 'imei'=>$imei,
  2792. 'created_at' => time(),
  2793. 'creator_id' => $userid,
  2794. 'device_id' => $dev_id
  2795. );
  2796. $config['id'] = M('send_config_log')->createAdd($log_data);
  2797. if (!$config['id']) {
  2798. json_fail('下发日志添加失败');
  2799. M()->rollback();
  2800. }
  2801. $redis->push(json_encode($config));
  2802. M()->commit();
  2803. json_success('设置成功');
  2804. }
  2805. public function delUserFence( ){
  2806. header('Access-Control-Allow-Origin: *');
  2807. $userid = I('get.userid');
  2808. if(!$userid){
  2809. json_fail('获取不到用户标识,尝试重登');
  2810. }
  2811. $fenceId =I('get.fenceId');
  2812. if(!$fenceId){
  2813. json_fail('获取不到围栏标识,尝试刷新');
  2814. }
  2815. $res = M('fences')->where(['id' => $fenceId, 'creator_id' => $userid, 'fence_type' => 1] )->delete();
  2816. if(!$res){
  2817. json_fail('删除失败');
  2818. }
  2819. json_success('删除成功');
  2820. }
  2821. public function sendReverveNotice( ){
  2822. header('Access-Control-Allow-Origin: *');
  2823. $voice_template_id=C('WX_VOICE_TEMPLATE_ID');
  2824. if(!$voice_template_id){
  2825. debug_log('voice_notice','WX_VOICE_TEMPLATE_ID not exist');
  2826. return false;
  2827. }
  2828. $data=$_POST;
  2829. $this->wxMsg = new \Jiaruan\WxTmp();
  2830. $access_token =$this->wxMsg->getAccessToken();
  2831. $msgArray= array(
  2832. "touser"=>$data['openid'],
  2833. "msgtype"=>"text",
  2834. "text"=>array(
  2835. "content"=>urlencode("测试啥是")
  2836. )
  2837. );
  2838. $json=urldecode(json_encode($msgArray));
  2839. //var_dump($json);exit;
  2840. #群发 文本消息
  2841. $ch = curl_init();
  2842. curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token);
  2843. curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
  2844. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2845. $res = json_decode(curl_exec($ch),true);
  2846. curl_close($ch);
  2847. json_success($res);
  2848. }
  2849. public function getMyInsureList( ){
  2850. header('Access-Control-Allow-Origin: *');
  2851. $openid = I('get.openid');
  2852. $userid = I('get.userid');
  2853. //检测登录状态
  2854. $res=$this->checkLoginState($openid,$userid);
  2855. if(!$res['status']){
  2856. json_fail($res['message']);
  2857. }
  2858. $vehiclesIds = M('vehicles')->where(['user_id' => $userid ])->getField('id',true);
  2859. $list=M('insure_records')->where(['vehicle_id' =>array('in',$vehiclesIds) ])->select();
  2860. foreach($list as &$val){
  2861. $start_at=strtotime(date('Y-m-d 00:00:00',$val['start_at']));
  2862. $end_at=strtotime(date('Y-m-d 23:59:59',$val['end_at']));
  2863. if(time()<$start_at){
  2864. $val['insure_state']=0;
  2865. $val['insure_state_text']='待生效';
  2866. }elseif(time()<=$end_at){
  2867. $val['insure_state']=1;
  2868. $val['insure_state_text']='生效中';
  2869. }else{
  2870. $val['insure_state']=2;
  2871. $val['insure_state_text']='已失效';
  2872. }
  2873. $val['vehicle_info']=M('vehicles')->where(['id' =>$val['vehicle_id']])->find();
  2874. $val['insure_info']=M('insurance')->where(['id' =>$val['insurance_id']])->find();
  2875. $val['start_at']=date('Y-m-d 00:00:00',$val['start_at']);
  2876. $val['end_at']=date('Y-m-d 23:59:59',$val['end_at']);
  2877. }
  2878. if(!$list){
  2879. json_fail('暂无保险');
  2880. }
  2881. json_success('查询成功',$list);
  2882. }
  2883. public function getInsureOptions( ){
  2884. header('Access-Control-Allow-Origin: *');
  2885. $list=M('insurance')->where(['enable' =>1])->field('*,name as text,id as value')->select();
  2886. foreach($list as &$val){
  2887. $val['price']=$val['price']*100;
  2888. }
  2889. json_success('查询成功',$list);
  2890. }
  2891. public function userByInsure( ){
  2892. header('Access-Control-Allow-Origin: *');
  2893. $openid = I('get.openid');
  2894. $userid = I('get.userid');
  2895. //检测登录状态
  2896. $res=$this->checkLoginState($openid,$userid);
  2897. if(!$res['status']){
  2898. json_fail($res['message']);
  2899. }
  2900. $data = json_decode( file_get_contents("php://input") ,true);
  2901. $insurance_data=M('insurance')->where(['id'=>$data['insure_id']])->find();
  2902. //添加保险记录信息
  2903. $insurance = array(
  2904. 'vehicle_id'=>$data['vehicle_id'],
  2905. 'insurance_id'=>$data['insure_id'],
  2906. 'start_at'=>strtotime(date('Y-m-d',strtotime('+1 day'))),
  2907. 'end_at'=>strtotime(date('Y-m-d',strtotime('+'.$insurance_data['years'].' year')))+24*3600-1,
  2908. 'creator_id'=>$userid,
  2909. 'created_at'=>time(),
  2910. 'updated_at'=>time()
  2911. );
  2912. if(!M('insure_records')->createAdd($insurance)){
  2913. json_fail('添加保险失败');
  2914. }
  2915. json_success('购买成功',$userid);
  2916. }
  2917. }