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