common.php 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142
  1. <?php
  2. if (!defined("CONFIG")) {
  3. die("Not defined");
  4. }
  5. require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/consts.php");
  6. require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/snmp.php");
  7. //ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
  8. //ValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
  9. //$ValidMacAddressRegex="^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}|([0-9a-fA-F]{4}[\\.-][0-9a-fA-F]{4}[\\.-][0-9a-fA-F]{4})|[0-9A-Fa-f]{12}$";
  10. $config["init"] = 0;
  11. // #### vendor id
  12. // 1, Unknown
  13. // 2, 'Eltex'
  14. // 3, 'Huawei'
  15. // 4, 'Zyxel'
  16. // 5, 'Raisecom'
  17. // 6, 'SNR'
  18. // 7, 'Dlink'
  19. // 8, 'Allied Telesis'
  20. // 9, 'Mikrotik'
  21. // 10, 'NetGear'
  22. // 11, 'Ubiquiti'
  23. // 15, 'HP'
  24. // 16, 'Cisco'
  25. // 17, 'Maipu'
  26. // 18, 'Asus'
  27. // Функция для безопасного получения параметров
  28. /*
  29. FILTER_DEFAULT // Без фильтрации (по умолчанию)
  30. FILTER_UNSAFE_RAW // Без фильтрации (аналогично FILTER_DEFAULT)
  31. FILTER_CALLBACK // Пользовательская функция обратного вызова
  32. FILTER_VALIDATE_BOOLEAN // true/false/1/0/"1"/"0"/"yes"/"no"
  33. FILTER_VALIDATE_EMAIL // Email адрес
  34. FILTER_VALIDATE_FLOAT // Число с плавающей точкой
  35. FILTER_VALIDATE_INT // Целое число
  36. FILTER_VALIDATE_IP // IP адрес (IPv4/IPv6)
  37. FILTER_VALIDATE_REGEXP // По регулярному выражению
  38. FILTER_VALIDATE_URL // URL адрес
  39. FILTER_VALIDATE_DOMAIN // Доменное имя (PHP 7.0+)
  40. FILTER_SANITIZE_EMAIL // Удаляет все кроме букв, цифр и !#$%&'*+-/=?^_`{|}~@.[]
  41. FILTER_SANITIZE_ENCODED // URL-encode строка
  42. FILTER_SANITIZE_MAGIC_QUOTES // Apply addslashes()
  43. FILTER_SANITIZE_NUMBER_FLOAT // Удаляет все кроме цифр, +- и .,eE
  44. FILTER_SANITIZE_NUMBER_INT // Удаляет все кроме цифр и +-
  45. FILTER_SANITIZE_SPECIAL_CHARS // HTML-escape '"<>& и символы с ASCII < 32
  46. FILTER_SANITIZE_FULL_SPECIAL_CHARS // Эквивалентно htmlspecialchars()
  47. FILTER_SANITIZE_STRING // Устарело - используйте FILTER_SANITIZE_FULL_SPECIAL_CHARS
  48. FILTER_SANITIZE_STRIPPED // Устарело
  49. FILTER_SANITIZE_URL // Удаляет все кроме букв, цифр и $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=
  50. Flags::
  51. // Для FILTER_VALIDATE_BOOLEAN
  52. FILTER_NULL_ON_FAILURE // Возвращает null вместо false при failure
  53. // Для FILTER_VALIDATE_INT
  54. FILTER_FLAG_ALLOW_OCTAL // Разрешает восьмеричные числа (0123)
  55. FILTER_FLAG_ALLOW_HEX // Разрешает шестнадцатеричные числа (0x1A)
  56. // Для FILTER_VALIDATE_FLOAT
  57. FILTER_FLAG_ALLOW_THOUSAND // Разрешает разделитель тысяч (1,234.56)
  58. FILTER_FLAG_ALLOW_SCIENTIFIC// Разрешает научную нотацию (1.2e3)
  59. // Для FILTER_VALIDATE_IP
  60. FILTER_FLAG_IPV4 // Только IPv4
  61. FILTER_FLAG_IPV6 // Только IPv6
  62. FILTER_FLAG_NO_PRIV_RANGE // Запрещает частные IP (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
  63. FILTER_FLAG_NO_RES_RANGE // Запрещает зарезервированные IP
  64. FILTER_FLAG_GLOBAL_RANGE // Разрешает только глобальные IP
  65. // Для FILTER_VALIDATE_URL
  66. FILTER_FLAG_PATH_REQUIRED // Требует наличие path (/page.html)
  67. FILTER_FLAG_QUERY_REQUIRED // Требует наличие query string (?id=1)
  68. // Для FILTER_SANITIZE_STRING
  69. FILTER_FLAG_NO_ENCODE_QUOTES // Не кодировать кавычки
  70. FILTER_FLAG_STRIP_LOW // Удаляет символы с ASCII < 32
  71. FILTER_FLAG_STRIP_HIGH // Удаляет символы с ASCII > 127
  72. FILTER_FLAG_ENCODE_LOW // Кодирует символы с ASCII < 32
  73. FILTER_FLAG_ENCODE_HIGH // Кодирует символы с ASCII > 127
  74. FILTER_FLAG_ENCODE_AMP // Кодирует амперсанд (&)
  75. */
  76. function capture_print_r($var) {
  77. ob_start();
  78. print_r($var);
  79. return ob_get_clean();
  80. }
  81. function needs_decoding($str) {
  82. // Проверяем, есть ли хотя бы один %-код, и корректен ли он
  83. return preg_match('/%[0-9A-Fa-f]{2}/', $str);
  84. }
  85. /**
  86. * Получает параметр только из GET (скаляр или массив)
  87. */
  88. function getGET($name, $page_url = null, $default = null, $filter = FILTER_DEFAULT, $options = []) {
  89. // Обработка массивов
  90. if (isset($_GET[$name]) && is_array($_GET[$name])) {
  91. return $_GET[$name];
  92. }
  93. // Проверяем, был ли параметр вообще передан
  94. if (!isset($_GET[$name])) {
  95. // Не передан — пробуем сессию
  96. if ($page_url !== null && isset($_SESSION[$page_url][$name])) {
  97. return $_SESSION[$page_url][$name];
  98. }
  99. return $default;
  100. }
  101. // Передан как пустая строка — сразу default
  102. if ($_GET[$name] === '') {
  103. return $default;
  104. }
  105. // Обычная фильтрация
  106. $value = filter_input(INPUT_GET, $name, $filter, $options);
  107. if ($value === false || $value === null) {
  108. return $default;
  109. }
  110. return $value;
  111. }
  112. /**
  113. * Получает параметр только из POST (скаляр или массив)
  114. */
  115. function getPOST($name, $page_url = null, $default = null, $filter = FILTER_DEFAULT, $options = []) {
  116. // Обработка массивов
  117. if (isset($_POST[$name]) && is_array($_POST[$name])) {
  118. return $_POST[$name];
  119. }
  120. // Проверяем, был ли параметр вообще передан
  121. if (!isset($_POST[$name])) {
  122. // Не передан — пробуем сессию
  123. if ($page_url !== null && isset($_SESSION[$page_url][$name])) {
  124. return $_SESSION[$page_url][$name];
  125. }
  126. return $default;
  127. }
  128. // Передан как пустая строка — сразу default
  129. if ($_POST[$name] === '') {
  130. return $default;
  131. }
  132. // Обычная фильтрация
  133. $value = filter_input(INPUT_POST, $name, $filter, $options);
  134. if ($value === false || $value === null) {
  135. return $default;
  136. }
  137. return $value;
  138. }
  139. /**
  140. * Получает параметр из POST или GET (скаляр или массив)
  141. * Приоритет: POST > GET
  142. */
  143. function getParam($name, $page_url = null, $default = null, $filter = FILTER_DEFAULT, $options = []) {
  144. // Сначала проверяем POST (массивы)
  145. if (isset($_POST[$name]) && is_array($_POST[$name])) {
  146. return $_POST[$name];
  147. }
  148. // Потом GET (массивы)
  149. if (isset($_GET[$name]) && is_array($_GET[$name])) {
  150. return $_GET[$name];
  151. }
  152. // Проверяем скалярные значения
  153. $post_exists = isset($_POST[$name]);
  154. $get_exists = isset($_GET[$name]);
  155. // Если параметр есть в POST
  156. if ($post_exists) {
  157. if ($_POST[$name] === '') {
  158. return $default;
  159. }
  160. $value = filter_input(INPUT_POST, $name, $filter, $options);
  161. if ($value !== false && $value !== null) {
  162. return $value;
  163. }
  164. return $default;
  165. }
  166. // Если параметр есть в GET
  167. if ($get_exists) {
  168. if ($_GET[$name] === '') {
  169. return $default;
  170. }
  171. $value = filter_input(INPUT_GET, $name, $filter, $options);
  172. if ($value !== false && $value !== null) {
  173. return $value;
  174. }
  175. return $default;
  176. }
  177. // Параметр не передан ни в POST, ни в GET — пробуем сессию
  178. if ($page_url !== null && isset($_SESSION[$page_url][$name])) {
  179. return $_SESSION[$page_url][$name];
  180. }
  181. return $default;
  182. }
  183. function intval_or_zero($v): int {
  184. return is_numeric($v) ? intval($v) : 0;
  185. }
  186. function normalize_vlan($vlan): int {
  187. $v = intval_or_zero($vlan);
  188. return ($v >= 1 && $v <= 4096) ? $v : 1;
  189. }
  190. function validate_dhcp_range(int $start, int $stop, int $net_start, int $net_stop): bool {
  191. if (!$start || !$stop) return false;
  192. if ($start >= $stop) return false;
  193. if ($start <= $net_start) return false;
  194. if ($stop >= $net_stop) return false;
  195. return true;
  196. }
  197. function get_dhcp_gateway($gw_raw, $fallback): int {
  198. $gw = ip2long(trim((string)$gw_raw));
  199. return $gw ? $gw : $fallback;
  200. }
  201. function safeUrlEncode($url) {
  202. // Сначала декодируем на случай двойного кодирования
  203. $decoded = urldecode($url);
  204. // Если после декодирования получили другой результат - значит был закодирован
  205. if ($decoded !== $url) {
  206. // Уже был закодирован - возвращаем декодированную версию
  207. return $url; // Или $decoded в зависимости от логики
  208. }
  209. // Не был закодирован - кодируем
  210. return urlencode($url);
  211. }
  212. function getSafeRedirectUrl(string $default = '/'): string {
  213. $url = filter_input(INPUT_GET, 'redirect_url', FILTER_SANITIZE_URL)
  214. ?? filter_input(INPUT_POST, 'redirect_url', FILTER_SANITIZE_URL)
  215. ?? $default;
  216. $default = safeUrlEncode($default);
  217. $decodedUrl = urldecode($url);
  218. // Проверяем:
  219. // 1. URL начинается с `/` (но не `//` или `http://`)
  220. // 2. Содержит только разрешённые символы (a-z, 0-9, -, _, /, ?, =, &, ., ~)
  221. if (!preg_match('/^\/(?!\/)[a-z0-9\-_\/?=&.~]*$/i', $decodedUrl)) {
  222. return $default;
  223. }
  224. // Проверяем:
  225. // 1. Начинается с /, не содержит //, ~, %00
  226. // 2. Разрешённые символы: a-z, 0-9, -, _, /, ?, =, &, .
  227. // 3. Допустимые форматы:
  228. // - /path/ (слэш на конце)
  229. // - /path (без слэша)
  230. // - /file.html (только .html)
  231. // - /script.php (только .php)
  232. // - Любой вариант с параметрами (?id=1)
  233. if (!preg_match(
  234. '/^\/' // Начинается с /
  235. . '(?!\/)' // Не //
  236. . '[a-z0-9\-_\/?=&.]*' // Разрешённые символы
  237. . '(?:\/' // Варианты окончаний:
  238. . '|\.(html|php)(?:\?[a-z0-9\-_=&]*)?' // .html/.php (+ параметры)
  239. . '|(?:\?[a-z0-9\-_=&]*)?' // Или параметры без расширения
  240. . ')$/i',
  241. $decodedUrl
  242. )) {
  243. return $default;
  244. }
  245. // Дополнительная защита: явно блокируем /config/, /vendor/ и т.д.
  246. if (preg_match('/(^|\/)(cfg|inc|log|sessions|tmp)(\/|$)/i', $decodedUrl)) {
  247. return $default;
  248. }
  249. return safeUrlEncode($url);
  250. }
  251. function randomPassword($length = 8)
  252. {
  253. $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  254. $pass = array(); //remember to declare $pass as an array
  255. $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
  256. for ($i = 0; $i < $length; $i++) {
  257. $n = rand(0, $alphaLength);
  258. $pass[] = $alphabet[$n];
  259. }
  260. return implode($pass); //turn the array into a string
  261. }
  262. if (!function_exists('mb_ucfirst')) {
  263. function mb_ucfirst(string $string, ?string $encoding = null): string
  264. {
  265. if ($string === '') {
  266. return '';
  267. }
  268. $encoding ??= mb_internal_encoding();
  269. $firstChar = mb_substr($string, 0, 1, $encoding);
  270. return mb_strtoupper($firstChar, $encoding) .
  271. mb_substr($string, 1, null, $encoding);
  272. }
  273. }
  274. function print_datetime($datetime) {
  275. if (is_empty_datetime($datetime)) { print "-"; } else { print $datetime; }
  276. }
  277. function get_datetime_display($datetime) {
  278. if (is_empty_datetime($datetime)) { return "-"; } else { return $datetime; }
  279. }
  280. function is_empty_datetime($datetime) {
  281. if (empty($datetime)) {
  282. return true;
  283. }
  284. // Проверяем формат даты и "нулевые" значения
  285. if ($datetime === '0000-00-00 00:00:00') {
  286. return true;
  287. }
  288. // Регулярное выражение для даты в формате YYYY-MM-DD HH:MM:SS
  289. if (!preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/', $datetime, $matches)) {
  290. return false; // Неверный формат — считаем валидным
  291. }
  292. $year = (int)$matches[1];
  293. $month = (int)$matches[2];
  294. $day = (int)$matches[3];
  295. $hour = (int)$matches[4];
  296. $minute = (int)$matches[5];
  297. $second = (int)$matches[6];
  298. // Проверяем, что дата в пределах "нулевого" диапазона
  299. // Unix epoch начинается с 1970-01-01 00:00:00 UTC
  300. // Но из-за часовых поясов могут быть варианты вроде 1970-01-01 03:00:00
  301. if ($year == 1970 && $month == 1 && $day == 1) {
  302. // Допускаем небольшой диапазон часов (0-12) как "нулевую" дату
  303. if ($hour >= 0 && $hour <= 12 && $minute == 0 && $second == 0) {
  304. return true;
  305. }
  306. }
  307. // Также проверяем даты до 1970 года (иногда бывают)
  308. if ($year < 1970) {
  309. return true;
  310. }
  311. return false;
  312. }
  313. function get_user_ip()
  314. {
  315. $auth_ip = getenv("HTTP_CLIENT_IP");
  316. if (empty($auth_ip)) {
  317. $auth_ip = getenv("HTTP_X_FORWARDED_FOR");
  318. if (empty($auth_ip)) {
  319. $auth_ip = getenv("REMOTE_ADDR");
  320. if (empty($auth_ip)) {
  321. $auth_ip = $_SERVER['REMOTE_ADDR'];
  322. }
  323. }
  324. }
  325. return $auth_ip;
  326. }
  327. /**
  328. * Преобразует строку вида "10G", "500M", "2k" в килобиты/с (целое число)
  329. *
  330. * @param string $bitrate_str Строка с битрейтом (например: "10G", "500M", "2k")
  331. * @return int Количество килобит/с (целое число)
  332. */
  333. function bitrate_to_kbps($bitrate_str) {
  334. if (!is_string($bitrate_str)) {
  335. return 0;
  336. }
  337. // Регулярное выражение: число (возможно с десятичной точкой) + необязательная единица
  338. if (!preg_match('/^(\d+(?:\.\d+)?)\s*([kMG])?$/i', $bitrate_str, $matches)) {
  339. return 0;
  340. }
  341. $value = (float)$matches[1];
  342. $unit = strtoupper($matches[2] ?? 'k');
  343. switch ($unit) {
  344. case 'G':
  345. return (int)($value * 1000000);
  346. case 'M':
  347. return (int)($value * 1000);
  348. case 'K':
  349. default:
  350. return (int)$value;
  351. }
  352. }
  353. /**
  354. * Преобразует килобиты/с в человекочитаемую строку (только целые значения)
  355. *
  356. * @param int $kbps Количество килобит/с
  357. * @return string Человекочитаемая строка (например: "10G", "500M", "2k")
  358. */
  359. function kbps_to_bitrate($kbps) {
  360. if (!is_numeric($kbps) || $kbps <= 0) {
  361. return "0k";
  362. }
  363. $kbps = (int)$kbps;
  364. if ($kbps >= 1000000) {
  365. return ($kbps / 1000000) . "G";
  366. } elseif ($kbps >= 1000) {
  367. return ($kbps / 1000) . "M";
  368. } else {
  369. return $kbps . "k";
  370. }
  371. }
  372. /**
  373. * Форматирует объём данных (в байтах) в человекочитаемый вид
  374. *
  375. * Функция преобразует числовое значение в байтах в строку с единицами измерения,
  376. * используя либо двоичную систему (KiB, MiB, GiB...) либо десятичную (kB, MB, GB...),
  377. * в зависимости от настройки системы.
  378. *
  379. * @param mixed $traff Объём данных в байтах (должен быть положительным числом)
  380. * @return string Отформатированная строка (например: "1.5 GiB", "2.3 MB", "0 B")
  381. *
  382. * @example
  383. * fbytes(1024) // "1 KiB" (если KB=1024) или "1.024 kB" (если KB=1000)
  384. * fbytes(1048576) // "1 MiB" или "1.049 MB"
  385. * fbytes(0) // "0 B"
  386. */
  387. function fbytes($traff)
  388. {
  389. // Определяем единицы измерения для двоичной системы (IEC 60027-2)
  390. // KiB = kibibyte (1024 bytes), MiB = mebibyte (1024^2 bytes), etc.
  391. $units_IEC = array(
  392. "", // bytes
  393. "Ki", // kibibytes
  394. "Mi", // mebibytes
  395. "Gi", // gibibytes
  396. "Ti" // tebibytes
  397. );
  398. // Определяем единицы измерения для десятичной системы (SI/metric)
  399. // kB = kilobyte (1000 bytes), MB = megabyte (1000^2 bytes), etc.
  400. $units_metric = array(
  401. "", // bytes
  402. "k", // kilobytes
  403. "M", // megabytes
  404. "G", // gigabytes
  405. "T" // terabytes
  406. );
  407. // Проверяем, что входное значение корректно (не пустое и положительное)
  408. if (!empty($traff) && $traff > 0) {
  409. // Определяем базу для расчётов: 1024 (двоичная) или 1000 (десятичная)
  410. // get_const('KB') должен возвращать true для двоичной системы (1024)
  411. // и false/null для десятичной системы (1000)
  412. $KB = get_const('KB');
  413. if ($KB) {
  414. $KB = 1024; // Двоичная система (IEC)
  415. } else {
  416. $KB = 1000; // Десятичная система (SI/metric)
  417. }
  418. // Выбираем соответствующую систему единиц измерения
  419. if ($KB == 1024) {
  420. // Двоичная система (IEC)
  421. // Определяем индекс единицы измерения: log_KB(traff)
  422. // Ограничиваем индекс максимальным доступным значением
  423. $index = min((int)log($traff, $KB), count($units_IEC) - 1);
  424. // Форматируем результат: значение + пробел + единица + "B"
  425. $result = round($traff / pow($KB, $index), 3) . ' ' . $units_IEC[$index] . 'B';
  426. } else {
  427. // Десятичная система (SI/metric)
  428. $index = min((int)log($traff, $KB), count($units_metric) - 1);
  429. $result = round($traff / pow($KB, $index), 3) . ' ' . $units_metric[$index] . 'B';
  430. }
  431. } else {
  432. // Для нулевого или некорректного значения возвращаем "0 B"
  433. $result = '0 B';
  434. }
  435. return $result;
  436. }
  437. function fpkts($packets)
  438. {
  439. $units = array(
  440. "",
  441. "k",
  442. "M",
  443. "G",
  444. "T"
  445. );
  446. if (!empty($packets) and $packets > 0) {
  447. $index = min(((int) log($packets, 1000)), count($units) - 1);
  448. $result = round($packets / pow(1000, $index), 3) . ' ' . $units[$index] . 'pkt/s';
  449. } else {
  450. $result = '0 pkt/s';
  451. }
  452. return $result;
  453. }
  454. function checkValidIp($cidr)
  455. {
  456. if (!is_string($cidr) || empty(trim($cidr))) {
  457. return false;
  458. }
  459. $cidr = trim($cidr);
  460. // Проверяем IPv4 CIDR
  461. if (preg_match('/^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$/', $cidr)) {
  462. return validateIPv4CIDR($cidr);
  463. }
  464. // Проверяем IPv6 CIDR
  465. if (preg_match('/^([0-9a-fA-F:]+)+(\/\d{1,3})?$/i', $cidr)) {
  466. return validateIPv6CIDR($cidr);
  467. }
  468. return false;
  469. }
  470. function validateIPv4CIDR($cidr)
  471. {
  472. $parts = explode("/", $cidr);
  473. $ip = $parts[0];
  474. $netmask = isset($parts[1]) ? (int)$parts[1] : 32;
  475. // Проверяем октеты
  476. $octets = explode(".", $ip);
  477. if (count($octets) !== 4) {
  478. return false;
  479. }
  480. foreach ($octets as $octet) {
  481. $octet = (int)$octet;
  482. if ($octet < 0 || $octet > 255) {
  483. return false;
  484. }
  485. }
  486. return $netmask >= 0 && $netmask <= 32;
  487. }
  488. // для IPv6
  489. function validateIPv6CIDR($cidr)
  490. {
  491. // Упрощенная проверка IPv6
  492. $parts = explode("/", $cidr);
  493. $ip = $parts[0];
  494. $netmask = isset($parts[1]) ? (int)$parts[1] : 128;
  495. return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false
  496. && $netmask >= 0 && $netmask <= 128;
  497. }
  498. function normalizeIpAddress($input) {
  499. // Заменяем все возможные варианты "ю" на стандартные точки
  500. $normalized = str_replace(
  501. ['ю', 'Ю', '>'], // Кириллические и латинские варианты
  502. '.',
  503. strtolower(trim($input))
  504. );
  505. if (!checkValidIp($normalized)) { return ''; }
  506. return $normalized;
  507. }
  508. function checkValidMac($mac)
  509. {
  510. if (!is_string($mac)) return false;
  511. $mac = trim($mac);
  512. // Отдельные шаблоны для каждого формата
  513. $patterns = [
  514. '/^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$/', // 00:1A:2B:3C:4D:5E
  515. '/^([0-9a-fA-F]{4}[\\.-]){2}[0-9a-fA-F]{4}$/', // 001A.2B3C.4D5E
  516. '/^[0-9A-Fa-f]{12}$/' // 001A2B3C4D5E
  517. ];
  518. foreach ($patterns as $pattern) {
  519. if (preg_match($pattern, $mac)) {
  520. return true;
  521. }
  522. }
  523. return false;
  524. }
  525. function MayBeMac($mac)
  526. {
  527. if (!is_string($mac)) {
  528. return;
  529. }
  530. // Оставляем только hex-символы
  531. $hex = preg_replace('/[^0-9a-f]/i', '', trim($mac));
  532. // Длина: от 2 до 6 октетов (4–12 hex-символов)
  533. if (!preg_match('/^[0-9a-f]{4,12}$/i', $hex)) {
  534. return;
  535. }
  536. // Чётное количество символов (целые октеты)
  537. if (strlen($hex) % 2 !== 0) {
  538. return;
  539. }
  540. return mac_dotted2($mac);
  541. }
  542. function mac_dotted2($mac)
  543. {
  544. if (!is_string($mac)) {
  545. return;
  546. }
  547. // оставляем только hex
  548. $hex = preg_replace('/[^0-9a-f]/i', '', trim($mac));
  549. // максимум 6 октетов = 12 hex
  550. if ($hex === '' || strlen($hex) > 12) {
  551. return;
  552. }
  553. // только целые октеты
  554. if (strlen($hex) % 2 !== 0) {
  555. return;
  556. }
  557. // разбиваем по 2 символа
  558. return implode(':', str_split(strtolower($hex), 2));
  559. }
  560. function checkValidHostname($dnsname)
  561. {
  562. if (empty($dnsname)) {
  563. return TRUE;
  564. }
  565. $host_pattern = "/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\.?$/";
  566. if (!preg_match($host_pattern, $dnsname)) {
  567. $result = FALSE;
  568. } else {
  569. $result = TRUE;
  570. }
  571. return $result;
  572. }
  573. function replaceSpecialChars($input) {
  574. // Заменяем ? на _ в любом месте
  575. $result = str_replace('?', '_', $input);
  576. // Заменяем * на % только в начале и конце с помощью регулярного выражения
  577. $result = preg_replace('/\*(?=.*.)/', '%', $result);
  578. return $result;
  579. }
  580. function searchHostname($db, $id, $hostname)
  581. {
  582. if (empty($hostname)) {
  583. return null;
  584. }
  585. $domain_zone = get_option($db, 33);
  586. $full_hostname = rtrim($hostname . '.' . ltrim($domain_zone, '.'), '.');
  587. $result_parts = [];
  588. // === Поиск A-записей в user_auth ===
  589. $a_sql = "SELECT id, ip FROM user_auth
  590. WHERE deleted = 0
  591. AND id != ?
  592. AND (dns_name = ? OR dns_name = ?)";
  593. $a_records = get_records_sql($db, $a_sql, [$id, $hostname, $full_hostname]);
  594. if (!empty($a_records)) {
  595. $a_list = [];
  596. foreach ($a_records as $rec) {
  597. $a_list[] = 'auth_id:' . $rec['id'] . ' ip: ' . $rec['ip'];
  598. }
  599. $result_parts[] = 'A-record: ' . implode('; ', $a_list) . ';';
  600. }
  601. // === Поиск CNAME-записей в user_auth_alias ===
  602. $cname_sql = "SELECT auth_id FROM user_auth_alias
  603. WHERE auth_id != ?
  604. AND (alias = ? OR alias = ?)";
  605. $cname_records = get_records_sql($db, $cname_sql, [$id, $hostname, $full_hostname]);
  606. if (!empty($cname_records)) {
  607. $cname_list = [];
  608. foreach ($cname_records as $rec) {
  609. $cname_list[] = 'auth_id:' . $rec['auth_id'];
  610. }
  611. $result_parts[] = 'CNAME-record: ' . implode(';', $cname_list) . ';';
  612. }
  613. return !empty($result_parts) ? trim(implode(' ', $result_parts)) : '';
  614. }
  615. function checkUniqHostname($db, $id, $hostname)
  616. {
  617. if (empty($hostname)) {
  618. return true;
  619. }
  620. $domain_zone = get_option($db, 33);
  621. $full_hostname = rtrim($hostname . '.' . ltrim($domain_zone, '.'), '.');
  622. // Проверка A-записей в user_auth
  623. $count_a = get_count_records($db, 'user_auth',
  624. 'deleted = 0 AND id != ? AND (dns_name = ? OR dns_name = ?)',
  625. [$id, $hostname, $full_hostname]
  626. );
  627. if ($count_a > 0) {
  628. return false;
  629. }
  630. // Проверка CNAME-записей в user_auth_alias
  631. $count_cname = get_count_records($db, 'user_auth_alias',
  632. 'auth_id != ? AND (alias = ? OR alias = ?)',
  633. [$id, $hostname, $full_hostname]
  634. );
  635. if ($count_cname > 0) {
  636. return false;
  637. }
  638. return true;
  639. }
  640. // Транслитерация строк.
  641. function transliterate($string, $gost = false)
  642. {
  643. if ($gost) {
  644. $replace = array(
  645. "А" => "A",
  646. "а" => "a",
  647. "Б" => "B",
  648. "б" => "b",
  649. "В" => "V",
  650. "в" => "v",
  651. "Г" => "G",
  652. "г" => "g",
  653. "Д" => "D",
  654. "д" => "d",
  655. "Е" => "E",
  656. "е" => "e",
  657. "Ё" => "E",
  658. "ё" => "e",
  659. "Ж" => "Zh",
  660. "ж" => "zh",
  661. "З" => "Z",
  662. "з" => "z",
  663. "И" => "I",
  664. "и" => "i",
  665. "Й" => "I",
  666. "й" => "i",
  667. "К" => "K",
  668. "к" => "k",
  669. "Л" => "L",
  670. "л" => "l",
  671. "М" => "M",
  672. "м" => "m",
  673. "Н" => "N",
  674. "н" => "n",
  675. "О" => "O",
  676. "о" => "o",
  677. "П" => "P",
  678. "п" => "p",
  679. "Р" => "R",
  680. "р" => "r",
  681. "С" => "S",
  682. "с" => "s",
  683. "Т" => "T",
  684. "т" => "t",
  685. "У" => "U",
  686. "у" => "u",
  687. "Ф" => "F",
  688. "ф" => "f",
  689. "Х" => "Kh",
  690. "х" => "kh",
  691. "Ц" => "Tc",
  692. "ц" => "tc",
  693. "Ч" => "Ch",
  694. "ч" => "ch",
  695. "Ш" => "Sh",
  696. "ш" => "sh",
  697. "Щ" => "Shch",
  698. "щ" => "shch",
  699. "Ы" => "Y",
  700. "ы" => "y",
  701. "Э" => "E",
  702. "э" => "e",
  703. "Ю" => "Iu",
  704. "ю" => "iu",
  705. "Я" => "Ia",
  706. "я" => "ia",
  707. "ъ" => "",
  708. "ь" => ""
  709. );
  710. } else {
  711. $arStrES = array(
  712. "ае",
  713. "уе",
  714. "ое",
  715. "ые",
  716. "ие",
  717. "эе",
  718. "яе",
  719. "юе",
  720. "ёе",
  721. "ее",
  722. "ье",
  723. "ъе",
  724. "ый",
  725. "ий"
  726. );
  727. $arStrOS = array(
  728. "аё",
  729. "уё",
  730. "оё",
  731. "ыё",
  732. "иё",
  733. "эё",
  734. "яё",
  735. "юё",
  736. "ёё",
  737. "её",
  738. "ьё",
  739. "ъё",
  740. "ый",
  741. "ий"
  742. );
  743. $arStrRS = array(
  744. "а$",
  745. "у$",
  746. "о$",
  747. "ы$",
  748. "и$",
  749. "э$",
  750. "я$",
  751. "ю$",
  752. "ё$",
  753. "е$",
  754. "ь$",
  755. "ъ$",
  756. "@",
  757. "@"
  758. );
  759. $replace = array(
  760. "А" => "A",
  761. "а" => "a",
  762. "Б" => "B",
  763. "б" => "b",
  764. "В" => "V",
  765. "в" => "v",
  766. "Г" => "G",
  767. "г" => "g",
  768. "Д" => "D",
  769. "д" => "d",
  770. "Е" => "Ye",
  771. "е" => "e",
  772. "Ё" => "Ye",
  773. "ё" => "e",
  774. "Ж" => "Zh",
  775. "ж" => "zh",
  776. "З" => "Z",
  777. "з" => "z",
  778. "И" => "I",
  779. "и" => "i",
  780. "Й" => "Y",
  781. "й" => "y",
  782. "К" => "K",
  783. "к" => "k",
  784. "Л" => "L",
  785. "л" => "l",
  786. "М" => "M",
  787. "м" => "m",
  788. "Н" => "N",
  789. "н" => "n",
  790. "О" => "O",
  791. "о" => "o",
  792. "П" => "P",
  793. "п" => "p",
  794. "Р" => "R",
  795. "р" => "r",
  796. "С" => "S",
  797. "с" => "s",
  798. "Т" => "T",
  799. "т" => "t",
  800. "У" => "U",
  801. "у" => "u",
  802. "Ф" => "F",
  803. "ф" => "f",
  804. "Х" => "Kh",
  805. "х" => "kh",
  806. "Ц" => "Ts",
  807. "ц" => "ts",
  808. "Ч" => "Ch",
  809. "ч" => "ch",
  810. "Ш" => "Sh",
  811. "ш" => "sh",
  812. "Щ" => "Shch",
  813. "щ" => "shch",
  814. "Ъ" => "",
  815. "ъ" => "",
  816. "Ы" => "Y",
  817. "ы" => "y",
  818. "Ь" => "",
  819. "ь" => "",
  820. "Э" => "E",
  821. "э" => "e",
  822. "Ю" => "Yu",
  823. "ю" => "yu",
  824. "Я" => "Ya",
  825. "я" => "ya",
  826. "@" => "y",
  827. "$" => "ye"
  828. );
  829. $string = str_replace($arStrES, $arStrRS, $string);
  830. $string = str_replace($arStrOS, $arStrRS, $string);
  831. }
  832. return strtr($string, $replace);
  833. }
  834. function cidrToRange($cidr)
  835. {
  836. $range = array();
  837. $cidr = explode('/', $cidr);
  838. $mask = isset($cidr[1]) ? (int)$cidr[1] : 32;
  839. if ($mask > 32) $mask = 32;
  840. $start = ip2long($cidr[0]) & (-1 << (32 - $mask));
  841. $stop = $start + (1 << (32 - $mask)) - 1;
  842. $range[0] = long2ip($start);
  843. $range[1] = long2ip($stop);
  844. $range[2] = $mask;
  845. // DHCP: выделяем половину диапазона по центру
  846. $total_hosts = $stop - $start;
  847. $dhcp_size = (int) round($total_hosts / 2.0);
  848. $dhcp_offset = (int) round($dhcp_size / 2.0);
  849. $dhcp_start = $start + $dhcp_offset;
  850. $range[3] = long2ip($dhcp_start);
  851. $range[4] = long2ip($dhcp_start + $dhcp_size);
  852. $range[5] = long2ip($start + 1);
  853. return $range;
  854. }
  855. function crypt_string($simple_string)
  856. {
  857. // Storin gthe cipher method
  858. $ciphering = "aes-128-cbc";
  859. // Using OpenSSl Encryption method
  860. $iv_length = openssl_cipher_iv_length($ciphering);
  861. $options = 0;
  862. // Using openssl_encrypt() function to encrypt the data
  863. return openssl_encrypt($simple_string, $ciphering, ENCRYPTION_KEY, $options, ENCRYPTION_IV);
  864. }
  865. function decrypt_string($crypted_string)
  866. {
  867. // Storin gthe cipher method
  868. $ciphering = "aes-128-cbc";
  869. // Using OpenSSl Encryption method
  870. $iv_length = openssl_cipher_iv_length($ciphering);
  871. $options = 0;
  872. // Using openssl_decrypt() function to decrypt the data
  873. return openssl_decrypt($crypted_string, $ciphering, ENCRYPTION_KEY, $options, ENCRYPTION_IV);
  874. }
  875. function print_instance_select($db, $instance_name, $instance_value)
  876. {
  877. echo "<select id=\"" . htmlspecialchars($instance_name) . "\" name=\"" . htmlspecialchars($instance_name) . "\">\n";
  878. $t_instance = get_records_sql($db, "SELECT id, name, description FROM filter_instances ORDER BY id");
  879. foreach ($t_instance as $row) {
  880. print_select_item($row['name'], $row['id'], $instance_value);
  881. }
  882. echo "</select>\n";
  883. }
  884. function get_subnet_description($db, $subnet_id)
  885. {
  886. if (empty($subnet_id)) {
  887. return '';
  888. }
  889. $subnet = get_record_sql($db, 'SELECT * FROM subnets WHERE id = ?', [(int)$subnet_id]);
  890. if (empty($subnet)) {
  891. return '';
  892. }
  893. $result = $subnet['subnet'] . '&nbsp;(' . $subnet['description'] . ')';
  894. return $result;
  895. }
  896. function get_filter_instance_description($db, $instance_id)
  897. {
  898. if (empty($instance_id)) {
  899. return '';
  900. }
  901. $instance = get_record_sql($db, 'SELECT * FROM filter_instances WHERE id = ?', [(int)$instance_id]);
  902. if (empty($instance)) {
  903. return '';
  904. }
  905. $result = $instance['name'] . '&nbsp;(' . $instance['description'] . ')';
  906. return $result;
  907. }
  908. function print_add_gw_subnets($db, $device_id, $gs_name)
  909. {
  910. echo "<select id=\"" . htmlspecialchars($gs_name) . "\" name=\"" . htmlspecialchars($gs_name) . "\">\n";
  911. $t_gs = get_records_sql($db,
  912. "SELECT id, subnet, description FROM subnets
  913. WHERE subnets.free = 0
  914. AND subnets.id NOT IN (SELECT subnet_id FROM gateway_subnets WHERE gateway_subnets.device_id = ?)
  915. ORDER BY subnet",
  916. [(int)$device_id]
  917. );
  918. if (!empty($t_gs)) {
  919. foreach ($t_gs as $row) {
  920. $display = htmlspecialchars($row['subnet']) . '(' . htmlspecialchars($row['description']) . ')';
  921. print_select_item($display, $row['id'], 0);
  922. }
  923. }
  924. echo "</select>\n";
  925. }
  926. function print_add_gw_instances($db, $device_id, $gs_name)
  927. {
  928. echo "<select id=\"" . htmlspecialchars($gs_name) . "\" name=\"" . htmlspecialchars($gs_name) . "\">\n";
  929. $t_gs = get_records_sql($db,
  930. "SELECT id, name, description FROM filter_instances
  931. WHERE filter_instances.id NOT IN (SELECT instance_id FROM device_filter_instances WHERE device_filter_instances.device_id = ?)
  932. ORDER BY name",
  933. [(int)$device_id]
  934. );
  935. if (!empty($t_gs)) {
  936. foreach ($t_gs as $row) {
  937. $display = htmlspecialchars($row['name']) . '(' . htmlspecialchars($row['description']) . ')';
  938. print_select_item($display, $row['id'], 0);
  939. }
  940. }
  941. echo "</select>\n";
  942. }
  943. function ninety_percent_rounded($number) {
  944. if (!is_numeric($number)) {
  945. return 0;
  946. }
  947. $ninety_percent = $number * 0.9;
  948. // Округляем до ближайшего десятка
  949. return round($ninety_percent / 10) * 10;
  950. }
  951. function print_add_dev_interface($db, $device_id, $int_list, $int_name)
  952. {
  953. echo "&nbsp;<select id=\"" . htmlspecialchars($int_name) . "\" name=\"" . htmlspecialchars($int_name) . "\">\n";
  954. $t_int = get_records_sql($db,
  955. "SELECT * FROM device_l3_interfaces WHERE device_id = ?",
  956. [(int)$device_id]
  957. );
  958. $int_exists = [];
  959. if (!empty($t_int)) {
  960. foreach ($t_int as $interface) {
  961. $int_exists[$interface['snmpin']] = $interface;
  962. }
  963. }
  964. foreach ($int_list as $interface) {
  965. if (!empty($int_exists[$interface['index']])) {
  966. continue;
  967. }
  968. $display_value = WEB_select_item_lan;
  969. if ($interface['interface_type'] == 1) {
  970. $display_value = WEB_select_item_wan;
  971. }
  972. // Отображаемое значение (видит пользователь) — экранируем
  973. $display_str = htmlspecialchars($interface['name']) . '&nbsp;|' .
  974. htmlspecialchars($interface['ip']) . '&nbsp;|' .
  975. htmlspecialchars(kbps_to_bitrate($interface['speed'])) . '|' .
  976. htmlspecialchars($display_value);
  977. // Значение (отправляется на сервер) — НЕ экранируем
  978. $value = $interface['name'] . ';' .
  979. $interface['index'] . ';' .
  980. $interface['interface_type'] . ';' .
  981. ninety_percent_rounded($interface['speed']);
  982. print_select_item($display_str, $value, 0);
  983. }
  984. echo "</select>\n";
  985. }
  986. function print_ou_select_recursive($db, $ou_name, $ou_value, $parent_id = null, $level = 0, $hide_zero_id = false)
  987. {
  988. // Ограничение глубины рекурсии: не более 3 уровней (0, 1, 2 → max level=2, следующий вызов будет level=3 и остановится)
  989. if ($level > 2) {
  990. return;
  991. }
  992. $params = [];
  993. if ($parent_id === null) {
  994. $sql = "SELECT id, parent_id, ou_name FROM ou WHERE (parent_id IS NULL OR parent_id = 0)";
  995. } else {
  996. $sql = "SELECT id, parent_id, ou_name FROM ou WHERE parent_id = ?";
  997. $params[] = (int)$parent_id;
  998. }
  999. if ($hide_zero_id) {
  1000. $sql .= " AND id != 0";
  1001. }
  1002. $sql .= " ORDER BY id";
  1003. $items = get_records_sql($db, $sql, $params);
  1004. if (empty($items)) {
  1005. return;
  1006. }
  1007. foreach ($items as $row) {
  1008. $indent = str_repeat("&nbsp;&nbsp;&nbsp;", $level);
  1009. $prefix = ($level > 0) ? $indent . "-&nbsp;" : "";
  1010. $display_name = $prefix . htmlspecialchars($row['ou_name']);
  1011. print_select_item($display_name, $row['id'], $ou_value);
  1012. // Рекурсивный вызов — только если уровень < 3
  1013. if ($level < 2) { // потому что следующий уровень будет $level + 1 = 3 → запрещён
  1014. print_ou_select_recursive($db, $ou_name, $ou_value, $row['id'], $level + 1, $hide_zero_id);
  1015. }
  1016. }
  1017. }
  1018. function print_ou_select($db, $ou_name, $ou_value)
  1019. {
  1020. echo "<select id=\"" . htmlspecialchars($ou_name) . "\" name=\"" . htmlspecialchars($ou_name) . "\">\n";
  1021. print_ou_select_recursive($db, $ou_name, $ou_value, null, 0, false);
  1022. echo "</select>\n";
  1023. }
  1024. function print_ou_set($db, $ou_name, $ou_value)
  1025. {
  1026. echo "<select id=\"" . htmlspecialchars($ou_name) . "\" name=\"" . htmlspecialchars($ou_name) . "\">\n";
  1027. print_ou_select_recursive($db, $ou_name, $ou_value, null, 0, true);
  1028. echo "</select>\n";
  1029. }
  1030. function print_subnet_select($db, $subnet_name, $subnet_value)
  1031. {
  1032. echo "<select id=\"" . htmlspecialchars($subnet_name) . "\" name=\"" . htmlspecialchars($subnet_name) . "\">\n";
  1033. $t_subnet = get_records_sql($db, "SELECT id, subnet FROM subnets ORDER BY ip_int_start");
  1034. print_select_item(WEB_select_item_all_ips, 0, $subnet_value);
  1035. if (!empty($t_subnet)) {
  1036. foreach ($t_subnet as $row) {
  1037. print_select_item(htmlspecialchars($row['subnet']), $row['id'], $subnet_value);
  1038. }
  1039. }
  1040. echo "</select>\n";
  1041. }
  1042. function print_acl_select($db, $acl_name, $acl_value)
  1043. {
  1044. echo "<select id=\"" . htmlspecialchars($acl_name) . "\" name=\"" . htmlspecialchars($acl_name) . "\">\n";
  1045. $t_acl = get_records_sql($db, "SELECT id, name FROM acl ORDER BY id");
  1046. if (!empty($t_acl)) {
  1047. foreach ($t_acl as $row) {
  1048. print_select_item(htmlspecialchars($row['name']), $row['id'], $acl_value);
  1049. }
  1050. }
  1051. echo "</select>\n";
  1052. }
  1053. function print_device_ip_select($db, $ip_name, $ip, $user_id)
  1054. {
  1055. echo "<select id=\"" . htmlspecialchars($ip_name) . "\" name=\"" . htmlspecialchars($ip_name) . "\">\n";
  1056. $auth_list = get_records_sql($db, "SELECT ip FROM user_auth WHERE user_id = ? AND deleted = 0 ORDER BY ip_int", [(int)$user_id]);
  1057. if (!empty($auth_list)) {
  1058. foreach ($auth_list as $row) {
  1059. // IP-адреса не требуют htmlspecialchars (они безопасны по формату)
  1060. print_select_item($row['ip'], $row['ip'], $ip);
  1061. }
  1062. }
  1063. echo "</select>\n";
  1064. }
  1065. function print_subnet_select_office($db, $subnet_name, $subnet_value)
  1066. {
  1067. echo "<select id=\"" . htmlspecialchars($subnet_name) . "\" name=\"" . htmlspecialchars($subnet_name) . "\">\n";
  1068. $t_subnet = get_records_sql($db, "SELECT id, subnet FROM subnets WHERE office = 1 ORDER BY ip_int_start");
  1069. print_select_item(WEB_select_item_all_ips, 0, $subnet_value);
  1070. if (!empty($t_subnet)) {
  1071. foreach ($t_subnet as $row) {
  1072. print_select_item(htmlspecialchars($row['subnet']), $row['id'], $subnet_value);
  1073. }
  1074. }
  1075. echo "</select>\n";
  1076. }
  1077. function print_subnet_select_office_splitted($db, $subnet_name, $subnet_value)
  1078. {
  1079. echo "<select id=\"" . htmlspecialchars($subnet_name) . "\" name=\"" . htmlspecialchars($subnet_name) . "\">\n";
  1080. $t_subnet = get_records_sql($db, "SELECT id, subnet, ip_int_start, ip_int_stop FROM subnets WHERE office = 1 ORDER BY ip_int_start");
  1081. print_select_item(WEB_select_item_all_ips, 0, $subnet_value);
  1082. foreach ($t_subnet as $row) {
  1083. // Основная подсеть
  1084. print_select_item(htmlspecialchars($row['subnet']), $row['subnet'], $subnet_value);
  1085. $cidr = cidrToRange($row['subnet']);
  1086. // $cidr[2] — это маска (например, 20)
  1087. if (!empty($cidr[2]) && $cidr[2] < 24) {
  1088. $f_start_ip = $row['ip_int_start'];
  1089. $f_stop_ip = $row['ip_int_stop'];
  1090. // Выравниваем начало до границы /24
  1091. $f_start_ip = floor($f_start_ip / 256) * 256;
  1092. while ($f_start_ip <= $f_stop_ip) {
  1093. $next_block_end = $f_start_ip + 255;
  1094. if ($next_block_end > $f_stop_ip) {
  1095. break;
  1096. }
  1097. $ip_24 = long2ip($f_start_ip) . "/24";
  1098. $display = "&nbsp;&nbsp;-&nbsp;" . htmlspecialchars($ip_24);
  1099. print_select_item($display, $ip_24, $subnet_value);
  1100. $f_start_ip += 256;
  1101. }
  1102. }
  1103. }
  1104. echo "</select>\n";
  1105. }
  1106. function print_loglevel_select($item_name, $value)
  1107. {
  1108. echo "<select id=\"" . htmlspecialchars($item_name) . "\" name=\"" . htmlspecialchars($item_name) . "\">\n";
  1109. print_select_item('Error', L_ERROR, $value);
  1110. print_select_item('Warning', L_WARNING, $value);
  1111. print_select_item('Info', L_INFO, $value);
  1112. print_select_item('Verbose', L_VERBOSE, $value);
  1113. print_select_item('Debug', L_DEBUG, $value);
  1114. echo "</select>\n";
  1115. }
  1116. function print_timeshift_select($value)
  1117. {
  1118. echo "<select id=\"date_shift\" name=\"date_shift\" onchange=\"updateDates()\">\n";
  1119. print_select_item('-', '-', $value);
  1120. print_select_item(WEB_date_shift_hour, 'h', $value);
  1121. print_select_item(WEB_date_shift_8hour, '8h', $value);
  1122. print_select_item(WEB_date_shift_day, 'd', $value);
  1123. print_select_item(WEB_date_shift_month, 'm', $value);
  1124. echo "</select>\n";
  1125. }
  1126. function print_date_fields($date1,$date2,$date_shift)
  1127. {
  1128. print WEB_log_start_date.'&nbsp'; print '<input type="datetime-local" name="date_start" id="date_start" value="'.$date1.'" onchange="SetDateShiftCustom()"/>';
  1129. print WEB_log_stop_date.'&nbsp'; print '<input type="datetime-local" name="date_stop" id="date_stop" value="'.$date2.'" onchange="SetDateShiftCustom()"/>';
  1130. print WEB_date_shift.'&nbsp'; print_timeshift_select($date_shift);
  1131. }
  1132. function reencodeurl($url)
  1133. {
  1134. $url_arr = explode('?', $url);
  1135. $fpage = $url_arr[0];
  1136. if (isset($url_arr[1])) {
  1137. $params = $url_arr[1];
  1138. $params_arr = explode('&', $params);
  1139. $new_params = '';
  1140. foreach ($params_arr as $row) {
  1141. $param = explode('=', $row);
  1142. $key = $param[0];
  1143. $value = urlencode(urldecode($param[1]));
  1144. $new_params .= "&" . $key . "=" . $value;
  1145. }
  1146. $new_params = preg_replace('/^&/', '', $new_params);
  1147. } else {
  1148. $new_params = '=';
  1149. }
  1150. if ($new_params === '=') {
  1151. $new_url = $fpage;
  1152. } else {
  1153. $new_url = $fpage . "?" . $new_params;
  1154. }
  1155. return $new_url;
  1156. }
  1157. function print_submenu_url($display_name, $page, $current_page, $last)
  1158. {
  1159. $url_arr = explode('?', $page);
  1160. $fpage = $url_arr[0];
  1161. $new_url = reencodeurl($page);
  1162. if ($fpage === $current_page) {
  1163. print "<b>$display_name</b>";
  1164. } else {
  1165. print "<a href='" . $new_url . "'> $display_name </a>";
  1166. }
  1167. if (!isset($last) or $last == 0) {
  1168. print " | ";
  1169. }
  1170. }
  1171. function print_submenu_nw($display_name, $page, $current_page, $last)
  1172. {
  1173. $url_arr = explode('?', $page);
  1174. $fpage = $url_arr[0];
  1175. $new_url = reencodeurl($page);
  1176. if ($fpage === $current_page) {
  1177. print "<b>$display_name</b>";
  1178. } else {
  1179. print '<a href="" onclick="window.open(\'' . $new_url . "', '_tab').focus(); return false;\">" . $display_name . "</a>";
  1180. }
  1181. if (!isset($last) or $last == 0) {
  1182. print " | ";
  1183. }
  1184. }
  1185. function print_url($display_name, $page, $class = '')
  1186. {
  1187. if (!empty($class)) { $class = "class='{$class}'"; }
  1188. print "<a $class href='" . reencodeurl($page) . "'> $display_name </a>";
  1189. }
  1190. function print_log_submenu($current_page)
  1191. {
  1192. print "<div id='submenu'>\n";
  1193. print_submenu_url(WEB_submenu_dhcp_log, '/admin/logs/dhcp.php', $current_page, 0);
  1194. print_submenu_url(WEB_submenu_work_log, '/admin/logs/index.php', $current_page, 0);
  1195. print_submenu_url(WEB_submenu_mac_history, '/admin/logs/mac.php', $current_page, 0);
  1196. print_submenu_url(WEB_submenu_ip_history, '/admin/logs/ip.php', $current_page, 0);
  1197. print_submenu_url(WEB_submenu_mac_unknown, '/admin/logs/unknown.php', $current_page, 0);
  1198. print_submenu_url(WEB_submenu_traffic, '/admin/logs/detaillog.php', $current_page, 0);
  1199. print_submenu_url(WEB_submenu_syslog, '/admin/logs/syslog.php', $current_page, 1);
  1200. print "</div>\n";
  1201. }
  1202. function print_control_submenu($current_page)
  1203. {
  1204. print "<div id='submenu'>\n";
  1205. print_submenu_url(WEB_submenu_control, '/admin/customers/control.php', $current_page, 0);
  1206. print_submenu_url(WEB_submenu_network, '/admin/customers/index-subnets.php', $current_page, 0);
  1207. print_submenu_url(WEB_submenu_network_stats, '/admin/customers/control-subnets-usage.php', $current_page, 0);
  1208. print_submenu_url(WEB_submenu_options, '/admin/customers/control-options.php', $current_page, 0);
  1209. print_submenu_url(WEB_submenu_customers, '/admin/customers/index.php', $current_page, 0);
  1210. print_submenu_url(WEB_submenu_buildings, '/admin/customers/building.php', $current_page, 0);
  1211. print_submenu_url(WEB_submenu_device_models, '/admin/customers/devmodels.php', $current_page, 0);
  1212. print_submenu_url(WEB_submenu_vendors, '/admin/customers/devvendors.php', $current_page, 1);
  1213. print "</div>\n";
  1214. }
  1215. function print_filters_submenu($current_page)
  1216. {
  1217. print "<div id='submenu'>\n";
  1218. print_submenu_url(WEB_submenu_filter_list, '/admin/filters/index.php', $current_page, 0);
  1219. print_submenu_url(WEB_submenu_filter_group, '/admin/filters/groups.php', $current_page, 0);
  1220. print_submenu_url(WEB_submenu_filter_instances, '/admin/filters/instances.php', $current_page, 1);
  1221. print "</div>\n";
  1222. }
  1223. function print_reports_submenu($current_page)
  1224. {
  1225. print "<div id='submenu'>\n";
  1226. print_submenu_url(WEB_submenu_traffic_ip_report, '/admin/reports/index-full.php', $current_page, 0);
  1227. print_submenu_url(WEB_submenu_traffic_login_report, '/admin/reports/index.php', $current_page, 0);
  1228. print_submenu_url(WEB_submenu_traffic_wan_report, '/admin/reports/wan.php', $current_page, 1);
  1229. print "</div>\n";
  1230. }
  1231. function print_trafdetail_submenu($current_page, $params, $description)
  1232. {
  1233. print "<div id='subsubmenu'>\n";
  1234. print "$description\n";
  1235. print_submenu_url(WEB_submenu_traffic_top10, '/admin/reports/userdaydetail.php' . "?$params", $current_page, 0);
  1236. print_submenu_url(WEB_submenu_detail_log, '/admin/reports/userdaydetaillog.php' . "?$params", $current_page, 1);
  1237. print "</div>\n";
  1238. }
  1239. function print_device_submenu($current_page)
  1240. {
  1241. print "<div id='submenu'>\n";
  1242. print_submenu_url(WEB_submenu_net_devices, '/admin/devices/index.php', $current_page, 0);
  1243. print_submenu_url(WEB_submenu_passive_net_devices, '/admin/devices/index-passive.php', $current_page, 0);
  1244. print_submenu_url(WEB_submenu_hierarchy, '/admin/devices/index-tree.php', $current_page, 0);
  1245. print_submenu_url(WEB_submenu_ports_vlan, '/admin/devices/portsbyvlan.php', $current_page, 1);
  1246. print "</div>\n";
  1247. }
  1248. function open_window_url($url)
  1249. {
  1250. return "window.open('" . $url . "', '_blank');";
  1251. }
  1252. function print_editdevice_submenu($current_page, $id, $dev_type, $dev_name = NULL)
  1253. {
  1254. print "<div id='subsubmenu'>\n";
  1255. $dev_id = '';
  1256. if (isset($id)) {
  1257. $dev_id = '?id=' . $id;
  1258. }
  1259. if (!empty($dev_name)) {
  1260. print "<b>" . $dev_name . "::</b>";
  1261. }
  1262. print_submenu_url(WEB_submenu_options, '/admin/devices/editdevice.php' . $dev_id, $current_page, 0);
  1263. if ($dev_type <= 2) {
  1264. print_submenu_url(WEB_submenu_ports, '/admin/devices/switchport.php' . $dev_id, $current_page, 0);
  1265. print_submenu_url(WEB_submenu_state, '/admin/devices/switchstatus.php' . $dev_id, $current_page, 0);
  1266. print_submenu_url(WEB_submenu_connections, '/admin/devices/switchport-conn.php' . $dev_id, $current_page, 1);
  1267. }
  1268. print "</div>\n";
  1269. }
  1270. function print_ip_submenu($current_page)
  1271. {
  1272. print "<div id='submenu'>\n";
  1273. print_submenu_url(WEB_submenu_ip_list, '/admin/iplist/index.php', $current_page, 0);
  1274. print_submenu_url(WEB_submenu_nagios, '/admin/iplist/nagios.php', $current_page, 0);
  1275. print_submenu_url(WEB_submenu_doubles, '/admin/iplist/doubles.php', $current_page, 0);
  1276. print_submenu_url(WEB_submenu_deleted, '/admin/iplist/deleted.php', $current_page, 0);
  1277. print_submenu_url(WEB_submenu_auto_rules, '/admin/iplist/auto_rules.php', $current_page, 1);
  1278. print "</div>\n";
  1279. }
  1280. function get_nagios_name($auth)
  1281. {
  1282. if (!empty($auth['dns_name'])) {
  1283. return $auth['dns_name'];
  1284. }
  1285. if (!empty($auth['dhcp_hostname'])) {
  1286. return $auth['dhcp_hostname'];
  1287. }
  1288. if (!empty($auth['description'])) {
  1289. $result = transliterate($auth['description']);
  1290. $result = preg_replace('/\(/', '-', $result);
  1291. $result = preg_replace('/\)/', '-', $result);
  1292. $result = preg_replace('/--/', '-', $result);
  1293. return $result;
  1294. }
  1295. if (empty($auth['login'])) {
  1296. $auth['login'] = 'host';
  1297. }
  1298. return $auth['login'] . "_" . $auth['id'];
  1299. }
  1300. function get_ou($db, $ou_value)
  1301. {
  1302. if (!isset($ou_value)) {
  1303. return null;
  1304. }
  1305. $ou_name = get_record_sql($db, "SELECT ou_name FROM ou WHERE id = ?", [(int)$ou_value]);
  1306. if (empty($ou_name)) {
  1307. return null;
  1308. }
  1309. return $ou_name['ou_name'];
  1310. }
  1311. function get_device_model($db, $model_value)
  1312. {
  1313. if (!isset($model_value)) {
  1314. return null;
  1315. }
  1316. $model_name = get_record_sql($db, "SELECT model_name FROM device_models WHERE id = ?", [(int)$model_value]);
  1317. if (empty($model_name)) {
  1318. return null;
  1319. }
  1320. return $model_name['model_name'];
  1321. }
  1322. function get_device_model_name($db, $model_value)
  1323. {
  1324. if (!isset($model_value)) {
  1325. return '';
  1326. }
  1327. $model_name = get_record_sql($db,
  1328. "SELECT M.id, M.model_name, V.name
  1329. FROM device_models M, vendors V
  1330. WHERE M.vendor_id = V.id AND M.id = ?",
  1331. [(int)$model_value]
  1332. );
  1333. if (empty($model_name)) {
  1334. return '';
  1335. }
  1336. return $model_name['name'] . ' ' . $model_name['model_name'];
  1337. }
  1338. function get_device_model_vendor($db, $model_value)
  1339. {
  1340. if (!isset($model_value)) {
  1341. return '';
  1342. }
  1343. $model_name = get_record_sql($db, "SELECT vendor_id FROM device_models WHERE id = ?", [(int)$model_value]);
  1344. if (empty($model_name)) {
  1345. return '';
  1346. }
  1347. return $model_name['vendor_id'];
  1348. }
  1349. function get_building($db, $building_value)
  1350. {
  1351. if (!isset($building_value)) {
  1352. return null;
  1353. }
  1354. $building_name = get_record_sql($db, "SELECT name FROM building WHERE id = ?", [(int)$building_value]);
  1355. if (empty($building_name)) {
  1356. return null;
  1357. }
  1358. return $building_name['name'];
  1359. }
  1360. function print_device_model_select($db, $device_model_name, $device_model_value)
  1361. {
  1362. echo "<select id=\"" . htmlspecialchars($device_model_name) . "\" name=\"" . htmlspecialchars($device_model_name) . "\" class=\"js-select-single\">\n";
  1363. $t_device_model = get_records_sql($db,
  1364. "SELECT M.id, M.model_name, V.name
  1365. FROM device_models M, vendors V
  1366. WHERE M.vendor_id = V.id
  1367. ORDER BY V.name, M.model_name"
  1368. );
  1369. foreach ($t_device_model as $row) {
  1370. $display = htmlspecialchars($row['name']) . " " . htmlspecialchars($row['model_name']);
  1371. print_select_item($display, $row['id'], $device_model_value);
  1372. }
  1373. echo "</select>\n";
  1374. }
  1375. function print_filter_group_select($db, $group_name, $group_value, $disabled = 0)
  1376. {
  1377. $disabled_attr = $disabled ? 'disabled' : '';
  1378. echo "<select id=\"" . htmlspecialchars($group_name) . "\" name=\"" . htmlspecialchars($group_name) . "\" {$disabled_attr}>\n";
  1379. $t_group = get_records_sql($db, "SELECT id, group_name FROM group_list ORDER BY group_name");
  1380. foreach ($t_group as $row) {
  1381. print_select_item(htmlspecialchars($row['group_name']), $row['id'], $group_value);
  1382. }
  1383. echo "</select>\n";
  1384. }
  1385. function print_building_select($db, $building_name, $building_value)
  1386. {
  1387. echo "<select id=\"" . htmlspecialchars($building_name) . "\" name=\"" . htmlspecialchars($building_name) . "\">\n";
  1388. print_select_item(WEB_select_item_all, 0, $building_value);
  1389. $t_building = get_records_sql($db, "SELECT id, name FROM building ORDER BY name");
  1390. foreach ($t_building as $row) {
  1391. print_select_item(htmlspecialchars($row['name']), $row['id'], $building_value);
  1392. }
  1393. echo "</select>\n";
  1394. }
  1395. function print_devmodels_select($db, $devmodel_name, $devmodel_value, $dev_filter = 'device_type<=2')
  1396. {
  1397. // Валидация фильтра для предотвращения SQL-инъекций
  1398. $allowed_filters = [
  1399. 'device_type<=2',
  1400. 'device_type=2',
  1401. 'device_type=1',
  1402. 'device_type=0'
  1403. ];
  1404. if (!in_array($dev_filter, $allowed_filters)) {
  1405. $dev_filter = 'device_type<=2';
  1406. }
  1407. echo "<select id=\"" . htmlspecialchars($devmodel_name) . "\" name=\"" . htmlspecialchars($devmodel_name) . "\">\n";
  1408. print_select_item(WEB_select_item_all, -1, $devmodel_value);
  1409. $t_devmodel = get_records_sql($db,
  1410. "SELECT M.id, V.name, M.model_name
  1411. FROM device_models M, vendors V
  1412. WHERE M.vendor_id = V.id
  1413. AND M.id IN (SELECT device_model_id FROM devices WHERE $dev_filter)
  1414. ORDER BY V.name, M.model_name"
  1415. );
  1416. if (!empty($t_devmodel)) {
  1417. foreach ($t_devmodel as $row) {
  1418. $display = htmlspecialchars($row['name']) . " " . htmlspecialchars($row['model_name']);
  1419. print_select_item($display, $row['id'], $devmodel_value);
  1420. }
  1421. }
  1422. echo "</select>\n";
  1423. }
  1424. function print_devtypes_select($db, $devtype_name, $devtype_value, $mode)
  1425. {
  1426. // Валидация режима для предотвращения SQL-инъекций
  1427. $allowed_modes = [
  1428. '',
  1429. 'device_class = 1',
  1430. 'device_class = 2',
  1431. 'device_class <= 2',
  1432. 'id IN (0,1,2)',
  1433. 'id > 0'
  1434. // Добавьте другие допустимые значения по необходимости
  1435. ];
  1436. if (!in_array($mode, $allowed_modes)) {
  1437. $mode = '';
  1438. }
  1439. echo "<select id=\"" . htmlspecialchars($devtype_name) . "\" name=\"" . htmlspecialchars($devtype_name) . "\">\n";
  1440. print_select_item(WEB_select_item_all, -1, $devtype_value);
  1441. $filter = '';
  1442. if (!empty($mode)) {
  1443. $filter = "WHERE $mode";
  1444. }
  1445. $lang_column = 'name_' . HTML_LANG;
  1446. $t_devtype = get_records_sql($db, "SELECT id, $lang_column FROM device_types $filter ORDER BY $lang_column");
  1447. if (!empty($t_devtype)) {
  1448. foreach ($t_devtype as $row) {
  1449. print_select_item(htmlspecialchars($row[$lang_column]), $row['id'], $devtype_value);
  1450. }
  1451. }
  1452. echo "</select>\n";
  1453. }
  1454. function print_devtype_select($db, $devtype_name, $devtype_value)
  1455. {
  1456. echo "<select id=\"" . htmlspecialchars($devtype_name) . "\" name=\"" . htmlspecialchars($devtype_name) . "\">\n";
  1457. $lang_column = 'name_' . HTML_LANG;
  1458. $t_devtype = get_records_sql($db, "SELECT id, $lang_column FROM device_types ORDER BY $lang_column");
  1459. foreach ($t_devtype as $row) {
  1460. print_select_item(htmlspecialchars($row[$lang_column]), $row['id'], $devtype_value);
  1461. }
  1462. echo "</select>\n";
  1463. }
  1464. function get_group($db, $group_value)
  1465. {
  1466. if (!isset($group_value)) {
  1467. return '';
  1468. }
  1469. $group = get_record_sql($db, "SELECT group_name FROM group_list WHERE id = ?", [(int)$group_value]);
  1470. if (!empty($group) && isset($group['group_name'])) {
  1471. return $group['group_name'];
  1472. }
  1473. return '';
  1474. }
  1475. function get_devtype_name($db, $device_type_id)
  1476. {
  1477. if (!isset($device_type_id)) {
  1478. return '';
  1479. }
  1480. $lang_column = 'name_' . HTML_LANG;
  1481. $type = get_record_sql($db, "SELECT $lang_column FROM device_types WHERE id = ?", [(int)$device_type_id]);
  1482. if (!empty($type) && isset($type[$lang_column])) {
  1483. return $type[$lang_column];
  1484. }
  1485. return '';
  1486. }
  1487. function get_l3_interfaces($db, $device_id)
  1488. {
  1489. $wan = '';
  1490. $lan = '';
  1491. $t_l3int = get_records_sql($db,
  1492. "SELECT name, interface_type FROM device_l3_interfaces WHERE device_id = ? ORDER BY name",
  1493. [(int)$device_id]
  1494. );
  1495. if (empty($t_l3int)) {
  1496. return '';
  1497. }
  1498. foreach ($t_l3int as $row) {
  1499. // Экранируем имя интерфейса для защиты от XSS при выводе
  1500. $name = htmlspecialchars($row['name']);
  1501. if ($row['interface_type'] == 0) {
  1502. $lan .= " " . $name;
  1503. }
  1504. if ($row['interface_type'] == 1) {
  1505. $wan .= " " . $name;
  1506. }
  1507. }
  1508. $wan = trim($wan);
  1509. $lan = trim($lan);
  1510. $result = '';
  1511. if (!empty($wan)) {
  1512. $result .= ' WAN: ' . $wan . '<br>';
  1513. }
  1514. if (!empty($lan)) {
  1515. $result .= ' LAN: ' . $lan;
  1516. }
  1517. return trim($result);
  1518. }
  1519. function get_wan_interfaces($db, $device_id)
  1520. {
  1521. $device_id = (int)$device_id;
  1522. // Получаем WAN-интерфейсы
  1523. $t_l3int = get_records_sql($db,
  1524. "SELECT id, name, snmpin FROM device_l3_interfaces
  1525. WHERE device_id = ? AND interface_type = 1
  1526. ORDER BY name",
  1527. [$device_id]
  1528. );
  1529. // Обрабатываем каждый интерфейс
  1530. foreach ($t_l3int as &$row) {
  1531. $row['description'] = '';
  1532. if (empty($row['snmpin'])) {
  1533. continue;
  1534. }
  1535. // Получаем описание порта
  1536. $conn = get_record_sql($db,
  1537. "SELECT description FROM device_ports
  1538. WHERE device_id = ? AND snmp_index = ?",
  1539. [$device_id, $row['snmpin']]
  1540. );
  1541. // Проверяем, есть ли комментарий в результатах запроса
  1542. if (!empty($conn) && !empty($conn['description'])) {
  1543. $row['description'] = htmlspecialchars($conn['description']);
  1544. }
  1545. }
  1546. unset($row);
  1547. return $t_l3int;
  1548. }
  1549. function get_gw_subnets($db, $device_id)
  1550. {
  1551. $gw_subnets = get_records_sql($db,
  1552. 'SELECT gateway_subnets.*, subnets.subnet, subnets.description
  1553. FROM gateway_subnets
  1554. LEFT JOIN subnets ON gateway_subnets.subnet_id = subnets.id
  1555. WHERE gateway_subnets.device_id = ?
  1556. ORDER BY subnets.subnet ASC',
  1557. [(int)$device_id]
  1558. );
  1559. if (empty($gw_subnets)) {
  1560. return '';
  1561. }
  1562. $result = '';
  1563. foreach ($gw_subnets as $row) {
  1564. if (!empty($row['subnet'])) {
  1565. $result .= ' ' . htmlspecialchars($row['subnet']) . '<br>';
  1566. }
  1567. }
  1568. return trim($result);
  1569. }
  1570. function print_queue_select($db, $queue_name, $queue_value, $disabled = 0)
  1571. {
  1572. $disabled_attr = $disabled ? 'disabled' : '';
  1573. echo "<select id=\"" . htmlspecialchars($queue_name) . "\" name=\"" . htmlspecialchars($queue_name) . "\" {$disabled_attr}>\n";
  1574. $t_queue = get_records_sql($db, "SELECT id, queue_name FROM queue_list ORDER BY queue_name");
  1575. foreach ($t_queue as $row) {
  1576. print_select_item(htmlspecialchars($row['queue_name']), $row['id'], $queue_value);
  1577. }
  1578. echo "</select>\n";
  1579. }
  1580. function get_queue($db, $queue_value)
  1581. {
  1582. if (!isset($queue_value)) {
  1583. return '';
  1584. }
  1585. $queue = get_record_sql($db, "SELECT queue_name FROM queue_list WHERE id = ?", [(int)$queue_value]);
  1586. if (!empty($queue) && isset($queue['queue_name'])) {
  1587. return $queue['queue_name'];
  1588. }
  1589. return '';
  1590. }
  1591. function print_qa_l3int_select($qa_name, $qa_value = 0)
  1592. {
  1593. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1594. print_select_item(WEB_select_item_lan, 0, $qa_value);
  1595. print_select_item(WEB_select_item_wan, 1, $qa_value);
  1596. print "</select>\n";
  1597. }
  1598. function print_qa_rule_select($qa_name, $qa_value = 1)
  1599. {
  1600. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1601. print_select_item('Subnet', 1, $qa_value);
  1602. print_select_item('Mac', 2, $qa_value);
  1603. print_select_item('Hostname', 3, $qa_value);
  1604. print "</select>\n";
  1605. }
  1606. function print_snmp_auth_proto_select($qa_name, $qa_value = 'sha512')
  1607. {
  1608. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1609. print_select_item('sha512', 'sha512', $qa_value);
  1610. print_select_item('sha256', 'sha256', $qa_value);
  1611. print_select_item('sha', 'sha', $qa_value);
  1612. print_select_item('md5', 'md5', $qa_value);
  1613. print "</select>\n";
  1614. }
  1615. function print_snmp_priv_proto_select($qa_name, $qa_value = 'aes128')
  1616. {
  1617. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1618. print_select_item('aes128', 'aes128', $qa_value);
  1619. print_select_item('aes', 'aes', $qa_value);
  1620. print_select_item('des', 'des', $qa_value);
  1621. print "</select>\n";
  1622. }
  1623. function get_int($qa_value = 0)
  1624. {
  1625. if (empty($qa_value)) {
  1626. $qa_value = 0;
  1627. } else {
  1628. $qa_value = (int)$qa_value * 1;
  1629. }
  1630. return $qa_value;
  1631. }
  1632. function print_qa_select($qa_name, $qa_value = 0, $disabled = 0)
  1633. {
  1634. $disabled_attr = $disabled ? 'disabled' : '';
  1635. print "<select name=\"$qa_name\" id=\"$qa_name\" {$disabled_attr}>\n";
  1636. if (empty($qa_value)) {
  1637. $qa_value = 0;
  1638. } else {
  1639. $qa_value = $qa_value * 1;
  1640. }
  1641. print_select_item(WEB_select_item_yes, 1, $qa_value);
  1642. print_select_item(WEB_select_item_no, 0, $qa_value);
  1643. print "</select>\n";
  1644. }
  1645. function print_list_select($qa_name, $qa_value, $list)
  1646. {
  1647. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1648. if (empty($qa_value)) {
  1649. $qa_value = '';
  1650. }
  1651. for ($i = 0; $i < count($list); ++$i) {
  1652. print_select_item($list[$i], $list[$i], $qa_value);
  1653. }
  1654. print "</select>\n";
  1655. }
  1656. function print_qa_select_ext($qa_name, $qa_value = 0, $readonly = 1)
  1657. {
  1658. $state = '';
  1659. if ($readonly) {
  1660. $state = 'disabled=true';
  1661. }
  1662. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1663. print_select_item_ext(WEB_select_item_yes, 1, $qa_value, $readonly);
  1664. print_select_item_ext(WEB_select_item_no, 0, $qa_value, $readonly);
  1665. print "</select>\n";
  1666. }
  1667. function print_td_yes_no($qa_value = 0, $text = FALSE)
  1668. {
  1669. $cl = 'down';
  1670. if ($qa_value == 1) { $cl = 'up'; }
  1671. // $cl = 'data';
  1672. if ($text) {
  1673. print "<td class=\"$cl\">";
  1674. if ($qa_value == 1) { print WEB_select_item_yes; } else { print WEB_select_item_no; }
  1675. print "</td>\n";
  1676. } else { print_td_qa($qa_value,FALSE,$cl); }
  1677. }
  1678. function print_yes_no($qa_value = 0, $yes_style = 'data', $no_style='data')
  1679. {
  1680. if ($qa_value) { $cl = $yes_style; } else { $cl = $no_style; }
  1681. print "<td class=\"$cl\">";
  1682. if ($qa_value == 1) {
  1683. print WEB_select_item_yes;
  1684. } else {
  1685. print WEB_select_item_no;
  1686. }
  1687. print "</td>\n";
  1688. }
  1689. function print_control_proto_select($qa_name, $qa_value = -1)
  1690. {
  1691. print "<select name=\"$qa_name\">\n";
  1692. print_select_item('Disabled', -1, $qa_value);
  1693. print_select_item('Ssh', 0, $qa_value);
  1694. print_select_item('Telnet', 1, $qa_value);
  1695. // print_select_item('Mikrotik rest api', 2, $qa_value);
  1696. print "</select>\n";
  1697. }
  1698. function print_snmp_select($qa_name, $qa_value = 0)
  1699. {
  1700. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1701. print_select_item('Disabled', 0, $qa_value);
  1702. print_select_item('v1', 1, $qa_value);
  1703. print_select_item('v2', 2, $qa_value);
  1704. print_select_item('v3', 3, $qa_value);
  1705. print "</select>\n";
  1706. }
  1707. function print_dhcp_select($qa_name, $qa_value = 0)
  1708. {
  1709. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1710. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1711. $qa_value = 'all';
  1712. }
  1713. print_select_item(WEB_select_item_events, 'all', $qa_value);
  1714. print_select_item(WEB_select_item_lease, 'add', $qa_value);
  1715. print_select_item(WEB_select_item_lease_refresh, 'old', $qa_value);
  1716. print_select_item(WEB_select_item_lease_free, 'del', $qa_value);
  1717. print "</select>\n";
  1718. }
  1719. function print_nagios_handler_select($db, $qa_name)
  1720. {
  1721. $nagios_handler = get_records_sql($db,
  1722. "SELECT DISTINCT nagios_handler FROM user_auth
  1723. WHERE nagios_handler IS NOT NULL AND nagios_handler != '' AND deleted = 0"
  1724. );
  1725. if (!empty($nagios_handler)) {
  1726. echo "<select name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1727. print_select_simple(WEB_select_item_no, '');
  1728. foreach ($nagios_handler as $handler) {
  1729. $value = htmlspecialchars($handler['nagios_handler']);
  1730. print_select_simple($value, $value);
  1731. }
  1732. echo "</select>\n";
  1733. } else {
  1734. echo "<input type=\"text\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"\" size=\"10\" />\n";
  1735. }
  1736. }
  1737. function print_dhcp_acl($db, $qa_name)
  1738. {
  1739. $dhcp_acl = get_records_sql($db,
  1740. "SELECT DISTINCT dhcp_acl FROM user_auth
  1741. WHERE dhcp_acl IS NOT NULL AND dhcp_acl != '' AND deleted = 0"
  1742. );
  1743. if (!empty($dhcp_acl)) {
  1744. echo "<select name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1745. print_select_simple(WEB_select_item_no, '');
  1746. foreach ($dhcp_acl as $acl) {
  1747. $value = htmlspecialchars($acl['dhcp_acl']);
  1748. print_select_simple($value, $value);
  1749. }
  1750. echo "</select>\n";
  1751. } else {
  1752. echo "<input type=\"text\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"\" size=\"10\" />\n";
  1753. }
  1754. }
  1755. function print_dhcp_option_set($db, $qa_name, $disabled = 0)
  1756. {
  1757. $disabled_attr = $disabled ? 'disabled' : '';
  1758. $dhcp_option_sets = get_records_sql($db,
  1759. "SELECT DISTINCT dhcp_option_set FROM user_auth
  1760. WHERE dhcp_option_set IS NOT NULL AND dhcp_option_set != '' AND deleted = 0"
  1761. );
  1762. if (!empty($dhcp_option_sets)) {
  1763. echo "<select name=\"" . htmlspecialchars($qa_name) . "\" {$disabled_attr}>\n";
  1764. print_select_simple(WEB_select_item_no, '');
  1765. foreach ($dhcp_option_sets as $dhcp_option_set) {
  1766. $value = htmlspecialchars($dhcp_option_set['dhcp_option_set']);
  1767. print_select_simple($value, $value);
  1768. }
  1769. echo "</select>\n";
  1770. } else {
  1771. echo "<input type=\"text\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"\" size=\"10\" />\n";
  1772. }
  1773. }
  1774. function print_dhcp_acl_list($db, $qa_name, $value = '', $disabled = 0)
  1775. {
  1776. $disabled_attr = $disabled ? 'disabled' : '';
  1777. $acl_values = [];
  1778. $dhcp_acl = get_records_sql($db,
  1779. "SELECT DISTINCT dhcp_acl FROM user_auth
  1780. WHERE dhcp_acl IS NOT NULL AND dhcp_acl != '' AND deleted = 0"
  1781. );
  1782. // Всегда добавляем 'hotspot-free'
  1783. $acl_values = ['hotspot-free'];
  1784. if (!empty($dhcp_acl)) {
  1785. foreach ($dhcp_acl as $acl) {
  1786. $val = trim($acl['dhcp_acl']);
  1787. if ($val !== '' && $val !== 'hotspot-free') {
  1788. $acl_values[] = $val;
  1789. }
  1790. }
  1791. }
  1792. echo "<input list=\"dhcp_acl\" id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"" . htmlspecialchars($value) . "\" {$disabled_attr}/>";
  1793. echo "<datalist id=\"dhcp_acl\">";
  1794. echo "<option value=\"\">";
  1795. foreach ($acl_values as $acl) {
  1796. echo "<option value=\"" . htmlspecialchars($acl) . "\">";
  1797. }
  1798. echo "</datalist>";
  1799. }
  1800. function print_dhcp_option_set_list($db, $qa_name, $value = '', $disabled = 0)
  1801. {
  1802. $disabled_attr = $disabled ? 'disabled' : '';
  1803. $option_values = [];
  1804. $dhcp_option_sets = get_records_sql($db,
  1805. "SELECT DISTINCT dhcp_option_set FROM user_auth
  1806. WHERE dhcp_option_set IS NOT NULL AND dhcp_option_set != '' AND deleted = 0"
  1807. );
  1808. if (!empty($dhcp_option_sets)) {
  1809. foreach ($dhcp_option_sets as $row) {
  1810. $val = trim($row['dhcp_option_set']);
  1811. if ($val !== '') {
  1812. $option_values[] = $val;
  1813. }
  1814. }
  1815. }
  1816. echo "<input list=\"dhcp_option_set\" id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"" . htmlspecialchars($value) . "\" {$disabled_attr}/>";
  1817. echo "<datalist id=\"dhcp_option_set\">";
  1818. echo "<option value=\"\">";
  1819. foreach ($option_values as $opt) {
  1820. echo "<option value=\"" . htmlspecialchars($opt) . "\">";
  1821. }
  1822. echo "</datalist>";
  1823. }
  1824. function print_enabled_select($qa_name, $qa_value)
  1825. {
  1826. // Убедимся, что значение корректно
  1827. if (!isset($qa_value) || $qa_value === '') {
  1828. $qa_value = 0;
  1829. } else {
  1830. $qa_value = (int)$qa_value;
  1831. }
  1832. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1833. print_select_item('-', 0, $qa_value);
  1834. print_select_item(WEB_select_item_disabled, 1, $qa_value);
  1835. print_select_item(WEB_select_item_enabled, 2, $qa_value);
  1836. echo "</select>\n";
  1837. }
  1838. function print_rule_target_select($qa_name, $qa_value)
  1839. {
  1840. // Убедимся, что значение корректно
  1841. if (!isset($qa_value) || $qa_value === '') {
  1842. $qa_value = 0;
  1843. } else {
  1844. $qa_value = (int)$qa_value;
  1845. }
  1846. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1847. print_select_item('-', 0, $qa_value);
  1848. print_select_item(WEB_rules_target_user, 1, $qa_value);
  1849. print_select_item(WEB_rules_target_group, 2, $qa_value);
  1850. echo "</select>\n";
  1851. }
  1852. function print_rule_type_select($qa_name, $qa_value)
  1853. {
  1854. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1855. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1856. $qa_value = 0;
  1857. }
  1858. print_select_item('-', 0, $qa_value);
  1859. print_select_item(WEB_rules_type_subnet, 1, $qa_value);
  1860. print_select_item(WEB_rules_type_mac, 2, $qa_value);
  1861. print_select_item(WEB_rules_type_hostname, 3, $qa_value);
  1862. print "</select>\n";
  1863. }
  1864. function print_yn_select($qa_name, $qa_value)
  1865. {
  1866. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1867. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1868. $qa_value = 0;
  1869. }
  1870. print_select_item('-', 0, $qa_value);
  1871. print_select_item(WEB_select_item_yes, 1, $qa_value);
  1872. print_select_item(WEB_select_item_no, 2, $qa_value);
  1873. print "</select>\n";
  1874. }
  1875. function print_ip_type_select($qa_name, $qa_value)
  1876. {
  1877. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1878. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1879. $qa_value = 0;
  1880. }
  1881. print_select_item(WEB_select_item_every, 0, $qa_value);
  1882. print_select_item(WEB_select_item_static, 1, $qa_value);
  1883. print_select_item(WEB_select_item_dhcp, 2, $qa_value);
  1884. print_select_item(WEB_select_item_suspicious, 3, $qa_value);
  1885. print "</select>\n";
  1886. }
  1887. function print_vendor_select($db, $qa_name, $qa_value, $disabled = 0)
  1888. {
  1889. $disabled_attr = $disabled ? 'disabled' : '';
  1890. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" style=\"width: 100%\" {$disabled_attr}>\n";
  1891. $vendors = get_records_sql($db, "SELECT id, name FROM vendors ORDER BY name");
  1892. print_select_item(WEB_select_item_all, 0, $qa_value);
  1893. foreach ($vendors as $row) {
  1894. print_select_item(htmlspecialchars($row['name']), $row['id'], $qa_value);
  1895. }
  1896. echo "</select>\n";
  1897. }
  1898. function print_vendor_set($db, $qa_name, $qa_value, $disabled = 0)
  1899. {
  1900. $disabled_attr = $disabled ? 'disabled' : '';
  1901. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" style=\"width: 100%\" {$disabled_attr}>\n";
  1902. $vendors = get_records_sql($db, "SELECT id, name FROM vendors ORDER BY name");
  1903. foreach ($vendors as $row) {
  1904. print_select_item(htmlspecialchars($row['name']), $row['id'], $qa_value);
  1905. }
  1906. echo "</select>\n";
  1907. }
  1908. function get_vendor_name($db, $v_id)
  1909. {
  1910. if (!isset($v_id)) {
  1911. return '';
  1912. }
  1913. $vendor = get_record_sql($db, "SELECT name FROM vendors WHERE id = ?", [(int)$v_id]);
  1914. if (!empty($vendor) && isset($vendor['name'])) {
  1915. return $vendor['name'];
  1916. }
  1917. return '';
  1918. }
  1919. function get_qa($qa_value, $text = FALSE)
  1920. {
  1921. if ($text) {
  1922. if ($qa_value == 1) { return "Да"; }
  1923. return "Нет";
  1924. } else {
  1925. if ($qa_value == 1) { return '<span style="font-size: 24px; font-weight: bold;">✓</span>'; }
  1926. return '<span style="font-size: 24px; font-weight: bold;">✗</span>';
  1927. }
  1928. }
  1929. function get_yes($qa_value, $text = FALSE)
  1930. {
  1931. if ($text) {
  1932. if ($qa_value == 1) { return "Да"; }
  1933. return "";
  1934. } else {
  1935. if ($qa_value == 1) { return '<span style="font-size: 16px; font-weight: bold;">✓</span>'; }
  1936. return "";
  1937. }
  1938. }
  1939. function print_td_qa ($qa_value, $text = FALSE, $parent_class = '')
  1940. {
  1941. $cl = "data_green";
  1942. if (!$qa_value) { $cl = "data_red"; }
  1943. print "<td class=\"$parent_class $cl\" >" . get_qa($qa_value,$text) . "</td>";
  1944. }
  1945. function print_td_yes ($qa_value, $text = FALSE, $parent_class = '')
  1946. {
  1947. $cl = "data_green";
  1948. if (!$qa_value) { $cl = "data_red"; }
  1949. print "<td class=\"$parent_class $cl\" >" . get_yes($qa_value,$text) . "</td>";
  1950. }
  1951. function print_action_select($action_name, $action_value)
  1952. {
  1953. print "<select id=\"$action_name\" name=\"$action_name\">\n";
  1954. print_select_item(WEB_select_item_allow, 1, $action_value);
  1955. print_select_item(WEB_select_item_forbidden, 0, $action_value);
  1956. print "</select>\n";
  1957. }
  1958. function get_action($action_value)
  1959. {
  1960. if ($action_value == 1) {
  1961. return "Разрешить";
  1962. }
  1963. return "Запретить";
  1964. }
  1965. function print_filter_select($db, $filter_name, $group_id)
  1966. {
  1967. echo "<select id=\"" . htmlspecialchars($filter_name) . "\" name=\"" . htmlspecialchars($filter_name) . "\" class=\"js-select-single\">\n";
  1968. if (isset($group_id)) {
  1969. $t_filters = get_records_sql($db,
  1970. "SELECT id, name FROM filter_list
  1971. WHERE id NOT IN (SELECT filter_id FROM group_filters WHERE group_id = ?)
  1972. ORDER BY name",
  1973. [(int)$group_id]
  1974. );
  1975. } else {
  1976. $t_filters = get_records_sql($db, "SELECT id, name FROM filter_list ORDER BY name");
  1977. }
  1978. foreach ($t_filters as $row) {
  1979. print_select_item(htmlspecialchars($row['name']), $row['id'], 0);
  1980. }
  1981. echo "</select>\n";
  1982. }
  1983. function get_filter($db, $filter_value)
  1984. {
  1985. if (!isset($filter_value)) {
  1986. return '';
  1987. }
  1988. $filter = get_record_sql($db, "SELECT name FROM filter_list WHERE id = ?", [(int)$filter_value]);
  1989. if (!empty($filter) && isset($filter['name'])) {
  1990. return $filter['name'];
  1991. }
  1992. return '';
  1993. }
  1994. function get_login($db, $user_id)
  1995. {
  1996. if (!isset($user_id)) {
  1997. return '';
  1998. }
  1999. $login = get_record_sql($db, "SELECT login FROM user_list WHERE id = ?", [(int)$user_id]);
  2000. if (!empty($login) && isset($login['login'])) {
  2001. return $login['login'];
  2002. }
  2003. return '';
  2004. }
  2005. function get_auth_count($db, $user_id)
  2006. {
  2007. if (!isset($user_id)) {
  2008. return 0;
  2009. }
  2010. $count = get_record_sql($db, "SELECT COUNT(id) as cnt FROM user_auth WHERE user_id = ? AND deleted = 0", [(int)$user_id]);
  2011. if (!empty($count) && isset($count['cnt'])) {
  2012. return (int)$count['cnt'];
  2013. }
  2014. return 0;
  2015. }
  2016. function print_login_select($db, $login_name, $current_login)
  2017. {
  2018. echo "<select id=\"" . htmlspecialchars($login_name) . "\" name=\"" . htmlspecialchars($login_name) . "\" class=\"js-select-single\">\n";
  2019. $t_login = get_records_sql($db, "SELECT id, login FROM user_list WHERE deleted=0 ORDER BY login");
  2020. print_select_item('None', 0, $current_login);
  2021. foreach ($t_login as $row) {
  2022. print_select_item(htmlspecialchars($row['login']), $row['id'], $current_login);
  2023. }
  2024. echo "</select>\n";
  2025. }
  2026. function print_auth_select($db, $login_name, $current_auth)
  2027. {
  2028. echo "<select id=\"" . htmlspecialchars($login_name) . "\" name=\"" . htmlspecialchars($login_name) . "\" class=\"js-select-single\">\n";
  2029. $params = [];
  2030. $sql = "SELECT U.login, U.description, A.ip, A.id
  2031. FROM user_list AS U, user_auth AS A
  2032. WHERE A.user_id = U.id
  2033. AND A.deleted = 0
  2034. AND (A.id NOT IN (SELECT device_ports.auth_id FROM device_ports) OR A.id = ?)
  2035. ORDER BY U.login, U.description, A.ip";
  2036. $params[] = (int)$current_auth;
  2037. $t_login = get_records_sql($db, $sql, $params);
  2038. print_select_item('Empty', 0, $current_auth);
  2039. foreach ($t_login as $row) {
  2040. $display = htmlspecialchars($row['login']) . "[" . htmlspecialchars($row['description']) . "] - " . htmlspecialchars($row['ip']);
  2041. print_select_item($display, $row['id'], $current_auth);
  2042. }
  2043. echo "</select>\n";
  2044. }
  2045. function print_auth_select_mac($db, $login_name, $current_auth)
  2046. {
  2047. echo "<select id=\"" . htmlspecialchars($login_name) . "\" name=\"" . htmlspecialchars($login_name) . "\" class=\"js-select-single\">\n";
  2048. $params = [];
  2049. $sql = "SELECT U.login, U.description, A.ip, A.mac, A.id
  2050. FROM user_list AS U, user_auth AS A
  2051. WHERE A.user_id = U.id
  2052. AND A.deleted = 0
  2053. AND (A.id NOT IN (SELECT device_ports.auth_id FROM device_ports) OR A.id = ?)
  2054. ORDER BY U.login, U.description, A.ip";
  2055. $params[] = (int)$current_auth;
  2056. $t_login = get_records_sql($db, $sql, $params);
  2057. print_select_item('Empty', 0, $current_auth);
  2058. foreach ($t_login as $row) {
  2059. $display = htmlspecialchars($row['login']) . "[" . htmlspecialchars($row['mac']) . "] - " . htmlspecialchars($row['ip']);
  2060. print_select_item($display, $row['id'], $current_auth);
  2061. }
  2062. echo "</select>\n";
  2063. }
  2064. function compact_port_name($port)
  2065. {
  2066. $result = $port;
  2067. $result = preg_replace('/XGigabitEthernet/', 'X', $result);
  2068. $result = preg_replace('/TenGigabitEthernet/', 'Te', $result);
  2069. $result = preg_replace('/GigabitEthernet/', 'Gi', $result);
  2070. return $result;
  2071. }
  2072. function print_device_port_select($db, $field_name, $device_id, $target_id)
  2073. {
  2074. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2075. $device_id = (int)$device_id;
  2076. $target_id = (int)$target_id;
  2077. $dpSQL = "
  2078. SELECT d.device_name,dp.port,dp.device_id,dp.id,dp.ifname
  2079. FROM devices d
  2080. JOIN device_ports dp
  2081. ON dp.device_id = d.id
  2082. WHERE d.deleted = 0
  2083. AND (dp.device_id <> ? OR dp.id = ?)
  2084. AND NOT EXISTS (
  2085. SELECT 1
  2086. FROM device_ports dp2
  2087. WHERE dp2.target_port_id = dp.id
  2088. AND dp2.target_port_id > 0
  2089. AND dp2.target_port_id <> ?
  2090. )
  2091. ORDER BY d.device_name, dp.port;
  2092. ";
  2093. $t_device = get_records_sql($db,$dpSQL,[$device_id, $target_id, $target_id]);
  2094. print_select_item('Empty', 0, $target_id);
  2095. foreach ($t_device as $row) {
  2096. $ifName = !empty($row['ifname']) ? $row['ifname'] : $row['port'];
  2097. $display = htmlspecialchars($row['device_name']) . "[" . htmlspecialchars($row['port']) . "] - " . htmlspecialchars(compact_port_name($ifName));
  2098. print_select_item($display, $row['id'], $target_id);
  2099. }
  2100. echo "</select>\n";
  2101. }
  2102. function print_device_select($db, $field_name, $device_id)
  2103. {
  2104. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2105. $t_device = get_records_sql($db,
  2106. "SELECT D.device_name, D.id
  2107. FROM devices AS D
  2108. WHERE D.deleted = 0
  2109. ORDER BY D.device_name ASC"
  2110. );
  2111. print_select_item(WEB_select_item_every, 0, $device_id);
  2112. foreach ($t_device as $row) {
  2113. print_select_item(htmlspecialchars($row['device_name']), $row['id'], $device_id);
  2114. }
  2115. echo "</select>\n";
  2116. }
  2117. function print_netdevice_select($db, $field_name, $device_id)
  2118. {
  2119. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2120. $t_device = get_records_sql($db,
  2121. "SELECT D.device_name, D.id
  2122. FROM devices AS D
  2123. WHERE D.deleted = 0 AND D.device_type <= 2
  2124. ORDER BY D.device_name ASC"
  2125. );
  2126. print_select_item(WEB_select_item_every, 0, $device_id);
  2127. foreach ($t_device as $row) {
  2128. print_select_item(htmlspecialchars($row['device_name']), $row['id'], $device_id);
  2129. }
  2130. echo "</select>\n";
  2131. }
  2132. function print_vlan_select($db, $field_name, $vlan)
  2133. {
  2134. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\" style=\"width: 100px;\">\n";
  2135. $v_device = get_records_sql($db, "SELECT DISTINCT vlan FROM device_ports ORDER BY vlan DESC");
  2136. if (!isset($vlan) || empty($vlan)) {
  2137. $vlan = 1;
  2138. }
  2139. print_select_item('1', 1, $vlan);
  2140. foreach ($v_device as $row) {
  2141. if ($row['vlan'] === '1') {
  2142. continue;
  2143. }
  2144. // VLAN-ы обычно числовые, но на всякий случай экранируем
  2145. $vlan_val = htmlspecialchars($row['vlan']);
  2146. print_select_item($vlan_val, $vlan_val, $vlan);
  2147. }
  2148. echo "</select>\n";
  2149. }
  2150. function print_device_select_ip($db, $field_name, $device_ip)
  2151. {
  2152. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2153. $t_device = get_records_sql($db,
  2154. "SELECT D.device_name, D.ip
  2155. FROM devices AS D
  2156. WHERE D.deleted = 0
  2157. ORDER BY D.device_name ASC"
  2158. );
  2159. print_select_item(WEB_select_item_every, '', $device_ip);
  2160. foreach ($t_device as $row) {
  2161. $display = htmlspecialchars($row['device_name']);
  2162. $value = htmlspecialchars($row['ip']); // IP безопасен, но для единообразия
  2163. print_select_item($display, $value, $device_ip);
  2164. }
  2165. echo "</select>\n";
  2166. }
  2167. function print_syslog_device_select($db, $field_name, $syslog_filter, $device_ip)
  2168. {
  2169. // Валидация фильтра для предотвращения SQL-инъекций
  2170. $allowed_filters = [
  2171. 'facility = 1',
  2172. 'facility = 2',
  2173. 'priority <= 3',
  2174. 'message LIKE "%error%"',
  2175. 'message LIKE "%warning%"',
  2176. '1=1' // для случая "все записи"
  2177. // Добавьте другие допустимые значения по необходимости
  2178. ];
  2179. if (!in_array($syslog_filter, $allowed_filters)) {
  2180. $syslog_filter = '1=1';
  2181. }
  2182. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2183. $t_device = get_records_sql($db,
  2184. "SELECT R.ip, D.device_name
  2185. FROM (SELECT DISTINCT ip FROM remote_syslog WHERE $syslog_filter) AS R
  2186. LEFT JOIN (SELECT ip, device_name FROM devices WHERE deleted = 0) AS D ON R.ip = D.ip
  2187. ORDER BY R.ip ASC"
  2188. );
  2189. print_select_item(WEB_select_item_every, '', $device_ip);
  2190. foreach ($t_device as $row) {
  2191. $display_name = !empty($row['device_name']) ? $row['device_name'] : $row['ip'];
  2192. $display = htmlspecialchars($display_name);
  2193. $value = htmlspecialchars($row['ip']);
  2194. print_select_item($display, $value, $device_ip);
  2195. }
  2196. echo "</select>\n";
  2197. }
  2198. function print_gateway_select($db, $field_name, $device_id)
  2199. {
  2200. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\">\n";
  2201. $t_device = get_records_sql($db,
  2202. "SELECT D.device_name, D.id
  2203. FROM devices AS D
  2204. WHERE D.deleted = 0 AND D.device_type = 2
  2205. ORDER BY D.device_name ASC"
  2206. );
  2207. print_select_item(WEB_select_item_every, 0, $device_id);
  2208. foreach ($t_device as $row) {
  2209. print_select_item(htmlspecialchars($row['device_name']), $row['id'], $device_id);
  2210. }
  2211. echo "</select>\n";
  2212. }
  2213. function get_gateways($db)
  2214. {
  2215. $t_device = get_records_sql($db,
  2216. "SELECT D.device_name, D.id
  2217. FROM devices AS D
  2218. WHERE D.deleted = 0 AND D.device_type = 2
  2219. ORDER BY D.device_name ASC"
  2220. );
  2221. $result = [];
  2222. foreach ($t_device as $row) {
  2223. $result[$row['id']] = $row['device_name'];
  2224. }
  2225. return $result;
  2226. }
  2227. function print_device_port($db, $target_id)
  2228. {
  2229. $t_device = get_records_sql($db,
  2230. "SELECT D.device_name, DP.port, DP.device_id
  2231. FROM devices AS D, device_ports AS DP
  2232. WHERE D.id = DP.device_id AND DP.id = ? AND D.deleted = 0",
  2233. [(int)$target_id]
  2234. );
  2235. foreach ($t_device as $row) {
  2236. $device_name = htmlspecialchars($row['device_name']);
  2237. $port = htmlspecialchars($row['port']);
  2238. $device_id = (int)$row['device_id'];
  2239. echo "<a href=\"/admin/devices/switchport.php?id={$device_id}\">{$device_name}[{$port}]</a>\n";
  2240. }
  2241. }
  2242. function get_device_ips($db, $device_id)
  2243. {
  2244. $switch = get_record($db, 'devices', 'id = ?', [(int)$device_id]);
  2245. $result = [];
  2246. if (!empty($switch['user_id'])) {
  2247. $auth_ips = get_records($db, 'user_auth', 'deleted = 0 AND user_id = ?', [(int)$switch['user_id']]);
  2248. foreach ($auth_ips as $value) {
  2249. if (isset($value['ip'])) {
  2250. $result[] = $value['ip'];
  2251. }
  2252. }
  2253. } else {
  2254. if (isset($switch['ip'])) {
  2255. $result[] = $switch['ip'];
  2256. }
  2257. }
  2258. return $result;
  2259. }
  2260. function get_device_id($db, $device_name)
  2261. {
  2262. if (empty($device_name)) {
  2263. return null;
  2264. }
  2265. $dev = get_record_sql($db,
  2266. "SELECT id FROM devices WHERE device_name = ? AND deleted = 0",
  2267. [$device_name]
  2268. );
  2269. if (empty($dev)) {
  2270. return null;
  2271. }
  2272. return $dev["id"];
  2273. }
  2274. function get_device_name($db, $device_id)
  2275. {
  2276. if (!isset($device_id)) {
  2277. return null;
  2278. }
  2279. $dev = get_record_sql($db,
  2280. "SELECT device_name FROM devices WHERE id = ?",
  2281. [(int)$device_id]
  2282. );
  2283. if (empty($dev)) {
  2284. return null;
  2285. }
  2286. return $dev["device_name"];
  2287. }
  2288. function get_auth_by_ip($db, $ip)
  2289. {
  2290. if (empty($ip)) {
  2291. return null;
  2292. }
  2293. $auth = get_record_sql($db,
  2294. "SELECT id FROM user_auth WHERE ip = ? AND deleted = 0",
  2295. [$ip]
  2296. );
  2297. if (empty($auth)) {
  2298. return null;
  2299. }
  2300. return $auth["id"];
  2301. }
  2302. function get_user_by_ip($db, $ip)
  2303. {
  2304. if (empty($ip)) {
  2305. return null;
  2306. }
  2307. $auth = get_record_sql($db,
  2308. "SELECT user_id FROM user_auth WHERE ip = ? AND deleted = 0",
  2309. [$ip]
  2310. );
  2311. if (empty($auth)) {
  2312. return null;
  2313. }
  2314. return $auth["user_id"];
  2315. }
  2316. function get_device_by_auth($db, $id)
  2317. {
  2318. if (!isset($id)) {
  2319. return null;
  2320. }
  2321. $f_dev = get_record_sql($db,
  2322. "SELECT id FROM devices WHERE user_id = ? AND deleted = 0",
  2323. [(int)$id]
  2324. );
  2325. if (empty($f_dev)) {
  2326. return null;
  2327. }
  2328. return $f_dev['id'];
  2329. }
  2330. function print_auth_port($db, $port_id, $new_window = false)
  2331. {
  2332. $t_auth = get_records_sql($db,
  2333. "SELECT A.ip, A.ip_int, A.mac, A.id, A.dns_name, A.user_id
  2334. FROM user_auth AS A, connections AS C
  2335. WHERE C.port_id = ? AND A.id = C.auth_id AND A.deleted = 0
  2336. ORDER BY A.ip_int",
  2337. [(int)$port_id]
  2338. );
  2339. foreach ($t_auth as $row) {
  2340. // Определяем отображаемое имя
  2341. $name = !empty($row['dns_name']) ? $row['dns_name'] : $row['ip'];
  2342. // Формируем title
  2343. $login = get_login($db, $row['user_id']);
  2344. $title = htmlspecialchars($login) . " =>" . htmlspecialchars($row['ip']) . "[" . htmlspecialchars($row['mac']) . "]";
  2345. if (!empty($row['dns_name'])) {
  2346. $title .= " | " . htmlspecialchars($row['dns_name']);
  2347. }
  2348. // Экранируем данные для вывода
  2349. $display_name = htmlspecialchars($name);
  2350. $display_ip = htmlspecialchars($row['ip']);
  2351. $auth_id = (int)$row['id'];
  2352. if ($new_window) {
  2353. $url = "/admin/users/editauth.php?id=" . $auth_id;
  2354. echo "<a href=\"\" title=\"" . $title . "\" onclick=\"" . open_window_url($url) . " return false;\">" . $display_name . " [" . $display_ip . "]</a><br>\n";
  2355. } else {
  2356. echo "<a href=\"/admin/users/editauth.php?id=" . $auth_id . "\" title=\"" . $title . "\">" . $display_name . " [" . $display_ip . "]</a><br>\n";
  2357. }
  2358. }
  2359. }
  2360. function get_port_description($db, $port_id, $port_description = '')
  2361. {
  2362. $t_auth = get_records_sql($db,
  2363. "SELECT A.ip_int, A.description
  2364. FROM user_auth AS A, connections AS C
  2365. WHERE C.port_id = ? AND A.id = C.auth_id AND A.deleted = 0
  2366. ORDER BY A.ip_int",
  2367. [(int)$port_id]
  2368. );
  2369. $description_found = false;
  2370. $result = '';
  2371. foreach ($t_auth as $row) {
  2372. $desc = !empty($row['description']) ? $row['description'] : '';
  2373. if (!empty($desc)) {
  2374. $description_found = true;
  2375. }
  2376. $result .= $desc . '<br>';
  2377. }
  2378. if (!$description_found) {
  2379. return $port_description;
  2380. }
  2381. if (!empty($port_description)) {
  2382. $result .= '(' . $port_description . ')';
  2383. }
  2384. return $result;
  2385. }
  2386. function print_auth_simple($db, $auth_id)
  2387. {
  2388. $auth = get_record($db, "user_auth", "id = ?", [(int)$auth_id]);
  2389. if (empty($auth)) {
  2390. return;
  2391. }
  2392. // Определяем отображаемое имя
  2393. $name = !empty($auth['dns_name']) ? $auth['dns_name'] :
  2394. (!empty($auth['description']) ? $auth['description'] : $auth['ip']);
  2395. $display_name = $name;
  2396. $safe_auth_id = (int)$auth_id;
  2397. echo "<a href=\"/admin/users/editauth.php?id={$safe_auth_id}\">{$display_name}</a><br>\n";
  2398. }
  2399. function print_auth($db, $auth_id)
  2400. {
  2401. $auth = get_record($db, "user_auth", "id = ?", [(int)$auth_id]);
  2402. if (empty($auth)) {
  2403. return;
  2404. }
  2405. // Формируем отображаемое имя
  2406. if (!empty($auth['dns_name'])) {
  2407. $name = $auth['dns_name'];
  2408. if (!empty($auth['description'])) {
  2409. $name .= " (" . $auth['description'] . ")";
  2410. }
  2411. } else {
  2412. $name = !empty($auth['description']) ? $auth['description'] : $auth['ip'];
  2413. }
  2414. if (!empty($name) && !empty($auth['ip'])) {
  2415. $name .= " [" . $auth['ip'] . "]";
  2416. }
  2417. $display_name = htmlspecialchars($name);
  2418. $safe_auth_id = (int)$auth_id;
  2419. echo "<a href=\"/admin/users/editauth.php?id={$safe_auth_id}\">{$display_name}</a><br>\n";
  2420. }
  2421. function print_auth_detail($db, $auth_id)
  2422. {
  2423. $auth = get_record($db, "user_auth", "id = ?", [(int)$auth_id]);
  2424. if (empty($auth)) {
  2425. return;
  2426. }
  2427. // Формируем отображаемое имя
  2428. if (!empty($auth['dns_name'])) {
  2429. $name = $auth['dns_name'];
  2430. if (!empty($auth['description'])) {
  2431. $name .= " (" . $auth['description'] . ")";
  2432. }
  2433. } else {
  2434. $name = !empty($auth['description']) ? $auth['description'] : $auth['ip'];
  2435. }
  2436. if (!empty($name) && !empty($auth['ip'])) {
  2437. $name .= " [" . $auth['ip'] . "]";
  2438. }
  2439. // Добавляем информацию о последнем обнаружении
  2440. if (!empty($auth['last_found'])) {
  2441. $name .= " last: [" . $auth['last_found'] . "] ";
  2442. }
  2443. // Добавляем статус удаления
  2444. if ($auth['deleted'] == 1) {
  2445. $name .= " <font color='red'>DELETED!!!</font>";
  2446. }
  2447. $display_name = htmlspecialchars($name);
  2448. $safe_auth_id = (int)$auth_id;
  2449. echo "<a href=\"/admin/users/editauth.php?id={$safe_auth_id}\">{$display_name}</a><br>\n";
  2450. }
  2451. function get_auth_port_count($db, $port_id)
  2452. {
  2453. $t_device = get_record_sql($db,
  2454. "SELECT COUNT(A.id) as cnt
  2455. FROM user_auth AS A, connections AS C
  2456. WHERE C.port_id = ? AND A.id = C.auth_id AND A.deleted = 0",
  2457. [(int)$port_id]
  2458. );
  2459. if (empty($t_device)) {
  2460. return 0;
  2461. }
  2462. return (int)$t_device['cnt'];
  2463. }
  2464. function get_connection($db, $auth_id)
  2465. {
  2466. $t_device = get_record_sql($db,
  2467. "SELECT D.device_name, DP.port
  2468. FROM devices AS D, device_ports AS DP, connections AS C
  2469. WHERE D.deleted = 0 AND D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id = ?",
  2470. [(int)$auth_id]
  2471. );
  2472. if (!empty($t_device) && isset($t_device['device_name'])) {
  2473. $device_name = expand_device_name($db, $t_device['device_name']);
  2474. $port = $t_device['port'];
  2475. return $device_name . "[" . $port . "]";
  2476. }
  2477. return '';
  2478. }
  2479. function get_connection_string($db, $auth_id)
  2480. {
  2481. $t_device = get_record_sql($db,
  2482. "SELECT D.device_name, DP.port
  2483. FROM devices AS D, device_ports AS DP, connections AS C
  2484. WHERE D.deleted = 0 AND D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id = ?",
  2485. [(int)$auth_id]
  2486. );
  2487. if (!empty($t_device) && isset($t_device['device_name'])) {
  2488. return $t_device['device_name'] . "[" . $t_device['port'] . "]";
  2489. }
  2490. return '';
  2491. }
  2492. function get_port($db, $port_id)
  2493. {
  2494. $t_device = get_record_sql($db,
  2495. "SELECT D.device_name, DP.port
  2496. FROM devices AS D, device_ports AS DP
  2497. WHERE D.deleted = 0 AND D.id = DP.device_id AND DP.id = ?",
  2498. [(int)$port_id]
  2499. );
  2500. if (!empty($t_device) && isset($t_device['device_name'])) {
  2501. $device_name = expand_device_name($db, $t_device['device_name']);
  2502. return $device_name . "[" . $t_device['port'] . "]";
  2503. }
  2504. return '';
  2505. }
  2506. function print_option_select($db, $option_name)
  2507. {
  2508. echo "<select id=\"" . htmlspecialchars($option_name) . "\" name=\"" . htmlspecialchars($option_name) . "\">\n";
  2509. // Неуникальные опции
  2510. $t_option = get_records_sql($db,
  2511. "SELECT id, option_name FROM config_options
  2512. WHERE uniq = 0 AND draft = 0 AND id != 68
  2513. ORDER BY option_name"
  2514. );
  2515. if (!empty($t_option)) {
  2516. foreach ($t_option as $row) {
  2517. echo "<option value=\"" . (int)$row['id'] . "\">" . htmlspecialchars($row['option_name']) . "</option>\n";
  2518. }
  2519. }
  2520. // Уникальные опции (которые ещё не используются)
  2521. $t_option = get_records_sql($db,
  2522. "SELECT id, option_name FROM config_options
  2523. WHERE draft = 0 AND uniq = 1 AND id != 68 AND id NOT IN (SELECT option_id FROM config WHERE draft = 0)
  2524. ORDER BY option_name"
  2525. );
  2526. if (!empty($t_option)) {
  2527. foreach ($t_option as $row) {
  2528. echo "<option value=\"" . (int)$row['id'] . "\">" . htmlspecialchars($row['option_name']) . "</option>\n";
  2529. }
  2530. }
  2531. echo "</select>\n";
  2532. }
  2533. function ResolveIP($db, $ip_int)
  2534. {
  2535. $ip_name = "-";
  2536. if (empty($ip_int)) {
  2537. return $ip_name;
  2538. }
  2539. // Проверяем кэш
  2540. $dns_cache = get_record_sql($db, "SELECT dns FROM dns_cache WHERE ip = ?", [(int)$ip_int]);
  2541. if (empty($dns_cache) || empty($dns_cache['dns'])) {
  2542. $ip_str = long2ip((int)$ip_int);
  2543. $ip_name = gethostbyaddr($ip_str);
  2544. // Проверяем результат разрешения
  2545. if (empty($ip_name) || $ip_name == $ip_str) {
  2546. $ip_name = "-";
  2547. }
  2548. // Сохраняем в кэш
  2549. run_sql($db, "INSERT INTO dns_cache(dns, ip) VALUES(?, ?)", [$ip_name, (int)$ip_int]);
  2550. } else {
  2551. $ip_name = $dns_cache['dns'];
  2552. }
  2553. return $ip_name;
  2554. }
  2555. function clean_dns_cache($db)
  2556. {
  2557. $date = time() - 86400; // 24 часа назад
  2558. $clean_date = date('Y-m-d H:i:s', $date);
  2559. run_sql($db, "DELETE FROM dns_cache WHERE ts <= ?", [$clean_date]);
  2560. }
  2561. function clean_unreferensed_rules($db)
  2562. {
  2563. run_sql($db, "DELETE FROM auth_rules WHERE user_id NOT IN (SELECT id FROM user_list)");
  2564. }
  2565. function FormatDateStr($format = 'Y-m-d H:i:s', $date_str)
  2566. {
  2567. $date1 = GetDateTimeFromString($date_str);
  2568. $result = $date1->format($format);
  2569. return $result;
  2570. }
  2571. function GetDateTimeFromString($date_str)
  2572. {
  2573. if (!is_a($date_str, 'DateTime')) {
  2574. $t_date_str = urldecode($date_str);
  2575. $t_date_str = preg_replace('/(\'|\")/', '', $t_date_str);
  2576. $t_date_str = preg_replace('/T/', ' ', $t_date_str);
  2577. $date1 = DateTime::createFromFormat('Y-m-d H:i:s', $t_date_str);
  2578. if (!$date1) {
  2579. $date1 = DateTime::createFromFormat('Y.m.d H:i:s', $t_date_str);
  2580. }
  2581. if (!$date1) {
  2582. $date1 = DateTime::createFromFormat('Y/m/d H:i:s', $t_date_str);
  2583. }
  2584. if (!$date1) {
  2585. $date1 = DateTime::createFromFormat('Y-m-d H:i', $t_date_str);
  2586. }
  2587. if (!$date1) {
  2588. $date1 = DateTime::createFromFormat('Y.m.d H:i', $t_date_str);
  2589. }
  2590. if (!$date1) {
  2591. $date1 = DateTime::createFromFormat('Y/m/d H:i', $t_date_str);
  2592. }
  2593. if (!$date1) {
  2594. $date1 = DateTime::createFromFormat('Y-m-d|', $t_date_str);
  2595. }
  2596. if (!$date1) {
  2597. $date1 = DateTime::createFromFormat('Y.m.d|', $t_date_str);
  2598. }
  2599. if (!$date1) {
  2600. $date1 = DateTime::createFromFormat('Y/m/d|', $t_date_str);
  2601. }
  2602. if (!$date1) {
  2603. $date1 = new DateTime;
  2604. $date1->setTime(0, 0, 0, 1);
  2605. }
  2606. } else {
  2607. return $date_str;
  2608. }
  2609. return $date1;
  2610. }
  2611. function GetNowTimeString()
  2612. {
  2613. $now = new DateTimeImmutable('now');
  2614. $result = $now->format('Y-m-d H:i:s');
  2615. return $result;
  2616. }
  2617. function GetNowDayString()
  2618. {
  2619. $now = new DateTimeImmutable('now');
  2620. $result = $now->format('Y-m-d');
  2621. return $result;
  2622. }
  2623. function get_ip_subnet($db, $ip)
  2624. {
  2625. if (empty($ip)) {
  2626. return null;
  2627. }
  2628. $ip_aton = ip2long($ip);
  2629. if ($ip_aton === false) {
  2630. return null;
  2631. }
  2632. // Исправлено: добавлены скобки для правильного порядка операций
  2633. $user_subnet = get_record_sql($db,
  2634. "SELECT * FROM subnets
  2635. WHERE (hotspot = 1 OR office = 1)
  2636. AND ? >= ip_int_start
  2637. AND ? <= ip_int_stop",
  2638. [$ip_aton, $ip_aton]
  2639. );
  2640. if (empty($user_subnet)) {
  2641. return null;
  2642. }
  2643. return $user_subnet;
  2644. }
  2645. function find_mac_in_subnet($db, $ip, $mac)
  2646. {
  2647. if (empty($ip) || empty($mac)) {
  2648. return null;
  2649. }
  2650. $ip_subnet = get_ip_subnet($db, $ip);
  2651. if (empty($ip_subnet)) {
  2652. return null;
  2653. }
  2654. $t_auth = get_records_sql($db,
  2655. "SELECT id, mac, user_id
  2656. FROM user_auth
  2657. WHERE ip_int >= ?
  2658. AND ip_int <= ?
  2659. AND mac = ?
  2660. AND deleted = 0
  2661. ORDER BY id",
  2662. [$ip_subnet['ip_int_start'], $ip_subnet['ip_int_stop'], $mac]
  2663. );
  2664. if (empty($t_auth)) {
  2665. return ['count' => 0, 'users_id' => []];
  2666. }
  2667. $result = ['count' => 0, 'users_id' => []];
  2668. foreach ($t_auth as $row) {
  2669. if (!empty($row['id'])) {
  2670. $result['count']++;
  2671. $result[$result['count']] = $row['id'];
  2672. $result['users_id'][] = $row['user_id'];
  2673. }
  2674. }
  2675. return $result;
  2676. }
  2677. function apply_auth_rule($db, $auth_record, $user_id)
  2678. {
  2679. if (empty($auth_record)) {
  2680. return null;
  2681. }
  2682. if (empty($user_id)) {
  2683. return $auth_record;
  2684. }
  2685. $user_rec = get_record($db, 'user_list', "id = ?", [(int)$user_id]);
  2686. if (empty($user_rec)) {
  2687. return $auth_record;
  2688. }
  2689. // Set filter and status by user
  2690. $auth_record['ou_id'] = $user_rec['ou_id'];
  2691. $auth_record['user_id'] = $user_rec['id'];
  2692. $auth_record['filter_group_id'] = $user_rec['filter_group_id'];
  2693. $auth_record['queue_id'] = $user_rec['queue_id'];
  2694. $auth_record['enabled'] = $user_rec['enabled'];
  2695. $auth_record['changed'] = 1;
  2696. // Maybe fill description?
  2697. if (!empty($user_rec['description']) && empty($auth_record['description'])) {
  2698. $auth_record['description'] = $user_rec['description'];
  2699. }
  2700. return $auth_record;
  2701. }
  2702. function fix_auth_rules($db)
  2703. {
  2704. // Cleanup hotspot subnet rules
  2705. $t_hotspot = get_records_sql($db, "SELECT id FROM ou WHERE default_users = 1 OR default_hotspot = 1");
  2706. if (!empty($t_hotspot)) {
  2707. foreach ($t_hotspot as $row) {
  2708. delete_record($db, "auth_rules", "ou_id = ?", [(int)$row['id']]);
  2709. }
  2710. }
  2711. $t_hotspot_subnets = get_records_sql($db, "SELECT subnet FROM subnets WHERE hotspot = 1");
  2712. if (!empty($t_hotspot_subnets)) {
  2713. foreach ($t_hotspot_subnets as $row) {
  2714. delete_record($db, "auth_rules", "rule = ?", [$row['subnet']]);
  2715. }
  2716. }
  2717. }
  2718. #---------------------------------------------------------------------------------------------------------------
  2719. function new_user($db, $user_info)
  2720. {
  2721. if (empty($user_info)) {
  2722. return null;
  2723. }
  2724. // Формируем логин и ФИО
  2725. if (!empty($user_info['mac'])) {
  2726. $user['login'] = mac_dotted($user_info['mac']);
  2727. } else {
  2728. $user['login'] = $user_info['ip'] ?? '';
  2729. }
  2730. if (!empty($user_info['dhcp_hostname'])) {
  2731. $user['description'] = ($user_info['ip'] ?? '') . '[' . $user_info['dhcp_hostname'] . ']';
  2732. } else {
  2733. $user['description'] = $user_info['ip'] ?? '';
  2734. }
  2735. // Проверяем существование логина и формируем уникальный
  2736. $base_login = $user['login'];
  2737. $login_count = get_count_records($db, "user_list",
  2738. "(login LIKE ?) OR (login = ?)",
  2739. [$base_login . '(%)', $base_login]
  2740. );
  2741. if (!empty($login_count) && $login_count > 0) {
  2742. $user['login'] = $base_login . "(" . ($login_count + 1) . ")";
  2743. }
  2744. // Назначаем OU и наследуем настройки
  2745. $user['ou_id'] = (int)($user_info['ou_id'] ?? 0);
  2746. if ($user['ou_id'] > 0) {
  2747. $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id = ?", [$user['ou_id']]);
  2748. if (!empty($ou_info)) {
  2749. $user['enabled'] = isset($ou_info['enabled']) ? (int)$ou_info['enabled'] : 0;
  2750. $user['queue_id'] = isset($ou_info['queue_id']) ? (int)$ou_info['queue_id'] : 0;
  2751. $user['filter_group_id'] = isset($ou_info['filter_group_id']) ? (int)$ou_info['filter_group_id'] : 0;
  2752. } else {
  2753. // Значения по умолчанию, если OU не найден
  2754. $user['enabled'] = 0;
  2755. $user['queue_id'] = 0;
  2756. $user['filter_group_id'] = 0;
  2757. }
  2758. } else {
  2759. // Значения по умолчанию при отсутствии OU
  2760. $user['enabled'] = 0;
  2761. $user['queue_id'] = 0;
  2762. $user['filter_group_id'] = 0;
  2763. }
  2764. // Создаём пользователя
  2765. $result = insert_record($db, "user_list", $user);
  2766. // Создаём автоматическое правило по MAC (если включено)
  2767. if (!empty($result)) {
  2768. $auto_mac_rule = (int)get_option($db, 64);
  2769. if ($auto_mac_rule && !empty($user_info['mac'])) {
  2770. $auth_rule = [
  2771. 'user_id' => $result,
  2772. 'rule_type' => 2,
  2773. 'rule' => mac_dotted($user_info['mac'])
  2774. ];
  2775. insert_record($db, "auth_rules", $auth_rule);
  2776. }
  2777. }
  2778. return $result;
  2779. }
  2780. function new_auth($db, $ip, $mac, $user_id)
  2781. {
  2782. if (empty($ip)) {
  2783. return null;
  2784. }
  2785. $ip_aton = ip2long($ip);
  2786. if ($ip_aton === false) {
  2787. return null;
  2788. }
  2789. $msg = '';
  2790. $user_id = (int)$user_id;
  2791. // Проверяем существование пары IP-MAC
  2792. if (!empty($mac)) {
  2793. $dotted_mac = mac_dotted($mac);
  2794. $auth_record = get_record_sql($db,
  2795. "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ? AND deleted = 0",
  2796. [$ip_aton, $dotted_mac]
  2797. );
  2798. if (!empty($auth_record)) {
  2799. LOG_WARNING($db, "Pair ip-mac already exists! Skip creating $ip [$mac] auth_id: " . $auth_record["id"]);
  2800. return $auth_record['id'];
  2801. }
  2802. }
  2803. // Настройки сохранения трафика
  2804. $save_traf = (int)get_option($db, 23);
  2805. $resurrection_id = null;
  2806. // Ищем удалённую запись с теми же IP и MAC
  2807. if (!empty($mac)) {
  2808. $old_auth_id = get_id_record($db, 'user_auth',
  2809. "deleted = 1 AND ip_int = ? AND mac = ?",
  2810. [$ip_aton, $mac]
  2811. );
  2812. } else {
  2813. $old_auth_id = get_id_record($db, 'user_auth',
  2814. "deleted = 1 AND ip_int = ? AND mac IS NULL",
  2815. [$ip_aton]
  2816. );
  2817. }
  2818. if (!empty($old_auth_id)) {
  2819. $resurrection_id = $old_auth_id;
  2820. $msg .= "Recovered auth_id: $resurrection_id with ip: $ip and mac: $mac ";
  2821. $auth = [
  2822. 'user_id' => $user_id,
  2823. 'deleted' => 0,
  2824. 'save_traf' => $save_traf
  2825. ];
  2826. update_record($db, "user_auth", "id = ?", $auth, [$resurrection_id]);
  2827. } else {
  2828. // Создаём новую запись
  2829. $msg .= "Create new ip record \r\nip: $ip\r\nmac: $mac\r\n";
  2830. $auth = [
  2831. 'deleted' => 0,
  2832. 'user_id' => $user_id,
  2833. 'ip' => $ip,
  2834. 'ip_int' => $ip_aton,
  2835. 'save_traf' => $save_traf
  2836. ];
  2837. if (!empty($mac)) {
  2838. $auth['mac'] = $mac;
  2839. }
  2840. $resurrection_id = insert_record($db, "user_auth", $auth);
  2841. }
  2842. // Применяем правила и обновляем запись
  2843. if (!empty($resurrection_id)) {
  2844. $auth_final = apply_auth_rule($db, $auth, $user_id);
  2845. update_record($db, "user_auth", "id = ?", $auth_final, [$resurrection_id]);
  2846. if (!is_hotspot($db, $ip) && !empty($msg)) {
  2847. LOG_WARNING($db, $msg);
  2848. }
  2849. if (is_hotspot($db, $ip) && !empty($msg)) {
  2850. LOG_INFO($db, $msg);
  2851. }
  2852. }
  2853. return $resurrection_id;
  2854. }
  2855. function resurrection_auth($db, $ip_record)
  2856. {
  2857. if (empty($ip_record) || empty($ip_record['ip'])) {
  2858. return null;
  2859. }
  2860. $ip = $ip_record['ip'];
  2861. $mac = $ip_record['mac'] ?? '';
  2862. $action = $ip_record['type'] ?? '';
  2863. $dhcp_hostname = $ip_record['hostname'] ?? '';
  2864. $hotspot_found = !empty($ip_record['hotspot']);
  2865. $ip_aton = ip2long($ip);
  2866. if ($ip_aton === false) {
  2867. return null;
  2868. }
  2869. // Проверяем существующую активную запись с теми же IP и MAC
  2870. $auth_record = get_record_sql($db,
  2871. "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ? AND deleted = 0",
  2872. [$ip_aton, $mac]
  2873. );
  2874. if (!empty($auth_record)) {
  2875. $user_info = get_record_sql($db,
  2876. "SELECT * FROM user_list WHERE id = ?",
  2877. [(int)$auth_record['user_id']]
  2878. );
  2879. LOG_DEBUG($db, "external dhcp user " . ($user_info['login'] ?? '') . " [" . $ip . "] auth_id: " . $auth_record['id']);
  2880. $auth_update = [];
  2881. if (isset($dhcp_hostname) && !empty($dhcp_hostname)) {
  2882. $auth_update['dhcp_hostname'] = $dhcp_hostname;
  2883. }
  2884. $auth_update['dhcp_action'] = $action;
  2885. $auth_update['dhcp_time'] = GetNowTimeString();
  2886. if ($action === 'add') {
  2887. $auth_update['last_found'] = GetNowTimeString();
  2888. }
  2889. update_record($db, "user_auth", "id = ?", $auth_update, [$auth_record['id']]);
  2890. return $auth_record['id'];
  2891. }
  2892. // Проверяем статическую подсеть
  2893. $ip_subnet = get_ip_subnet($db, $ip);
  2894. if (!empty($ip_subnet) && !empty($ip_subnet['static'])) {
  2895. LOG_WARNING($db, "Unknown pair ip+mac in static subnet! ip: $ip mac: [" . mac_dotted($mac) . "]. Skip");
  2896. return null;
  2897. }
  2898. $msg = '';
  2899. // Ищем запись с тем же IP (возможно, другой MAC)
  2900. $auth_record = get_record_sql($db,
  2901. "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0",
  2902. [$ip_aton]
  2903. );
  2904. if (!empty($auth_record)) {
  2905. if (empty($auth_record['mac'])) {
  2906. // Обновляем пустой MAC
  2907. $auth_update = [
  2908. 'mac' => mac_dotted($mac),
  2909. 'dhcp_action' => $action,
  2910. 'dhcp_time' => GetNowTimeString()
  2911. ];
  2912. if (!empty($dhcp_hostname)) {
  2913. $auth_update['dhcp_hostname'] = $dhcp_hostname;
  2914. }
  2915. if ($action === 'add') {
  2916. $auth_update['last_found'] = GetNowTimeString();
  2917. }
  2918. LOG_INFO($db, "for ip: $ip mac not found! Use empty record...");
  2919. update_record($db, "user_auth", "id = ?", $auth_update, [$auth_record['id']]);
  2920. return $auth_record['id'];
  2921. } else {
  2922. // MAC изменился - помечаем старую запись как удалённую
  2923. if (!$hotspot_found) {
  2924. LOG_WARNING($db, "for ip: $ip mac change detected! Old mac: [" . $auth_record['mac'] . "] New mac: [" . mac_dotted($mac) . "]. Disable old auth_id: " . $auth_record['id']);
  2925. }
  2926. update_record($db, "user_auth", "id = ?", ['changed' => 1, 'deleted' => 1], [$auth_record['id']]);
  2927. }
  2928. }
  2929. // Создаём/находим пользователя
  2930. $new_user_info = get_new_user_id($db, $ip, $mac, $dhcp_hostname);
  2931. $new_user_id = null;
  2932. if (!empty($new_user_info['user_id'])) {
  2933. $new_user_id = $new_user_info['user_id'];
  2934. }
  2935. if (empty($new_user_id)) {
  2936. $new_user_id = new_user($db, $new_user_info);
  2937. }
  2938. if (empty($new_user_id)) {
  2939. return null;
  2940. }
  2941. $new_user_id = (int)$new_user_id;
  2942. $save_traf = (int)get_option($db, 23);
  2943. $resurrection_id = null;
  2944. // Ищем удалённую запись с теми же IP и MAC для восстановления
  2945. $auth_record = get_record_sql($db,
  2946. "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ?",
  2947. [$ip_aton, $mac]
  2948. );
  2949. if (!empty($auth_record)) {
  2950. // Восстанавливаем существующую запись
  2951. $resurrection_id = $auth_record['id'];
  2952. $msg .= "Recovered auth_id: $resurrection_id with ip: $ip and mac: $mac ";
  2953. $auth = [
  2954. 'dhcp_action' => $action,
  2955. 'user_id' => $new_user_id,
  2956. 'deleted' => 0,
  2957. 'dhcp_time' => GetNowTimeString(),
  2958. 'save_traf' => $save_traf
  2959. ];
  2960. if (!empty($dhcp_hostname)) {
  2961. $auth['dhcp_hostname'] = $dhcp_hostname;
  2962. }
  2963. if ($action === 'add') {
  2964. $auth['last_found'] = GetNowTimeString();
  2965. }
  2966. update_record($db, "user_auth", "id = ?", $auth, [$resurrection_id]);
  2967. } else {
  2968. // Создаём новую запись
  2969. $msg .= "Создаём новый ip-адрес \r\nip: $ip\r\nmac: $mac\r\n";
  2970. $auth = [
  2971. 'deleted' => 0,
  2972. 'user_id' => $new_user_id,
  2973. 'ip' => $ip,
  2974. 'ip_int' => $ip_aton,
  2975. 'mac' => $mac,
  2976. 'dhcp_action' => $action,
  2977. 'dhcp_time' => GetNowTimeString(),
  2978. 'save_traf' => $save_traf
  2979. ];
  2980. if (!empty($dhcp_hostname)) {
  2981. $auth['dhcp_hostname'] = $dhcp_hostname;
  2982. }
  2983. if ($action === 'add') {
  2984. $auth['last_found'] = GetNowTimeString();
  2985. }
  2986. $resurrection_id = insert_record($db, "user_auth", $auth);
  2987. }
  2988. // Применяем правила авторизации
  2989. if (!empty($resurrection_id)) {
  2990. $auth_final = apply_auth_rule($db, $auth, $new_user_id);
  2991. update_record($db, "user_auth", "id = ?", $auth_final, [$resurrection_id]);
  2992. $msg .= "filter: " . ($auth_final['filter_group_id'] ?? '') .
  2993. "\r\n queue_id: " . ($auth_final['queue_id'] ?? '') .
  2994. "\r\n enabled: " . ($auth_final['enabled'] ?? '') .
  2995. "\r\nid: $resurrection_id";
  2996. if (!$hotspot_found && !empty($msg)) {
  2997. LOG_WARNING($db, $msg);
  2998. }
  2999. if ($hotspot_found && !empty($msg)) {
  3000. LOG_INFO($db, $msg);
  3001. }
  3002. }
  3003. return $resurrection_id;
  3004. }
  3005. function get_auth($db, $current_auth)
  3006. {
  3007. if (!isset($current_auth) || $current_auth == 0) {
  3008. return null;
  3009. }
  3010. $t_login = get_record_sql($db,
  3011. "SELECT U.login, A.ip
  3012. FROM user_list AS U, user_auth AS A
  3013. WHERE A.user_id = U.id AND A.id = ?",
  3014. [(int)$current_auth]
  3015. );
  3016. if (!empty($t_login) && isset($t_login['login'])) {
  3017. return $t_login['login'] . "[" . $t_login['ip'] . "]";
  3018. }
  3019. return '';
  3020. }
  3021. function get_auth_by_mac($db, $mac)
  3022. {
  3023. if (empty($mac)) {
  3024. return ['auth' => 'Unknown', 'mac' => ''];
  3025. }
  3026. $mac_dotted = mac_dotted($mac);
  3027. $t_login = get_record_sql($db,
  3028. "SELECT U.id, U.login, A.id as auth_id, A.ip
  3029. FROM user_list AS U, user_auth AS A
  3030. WHERE A.user_id = U.id AND A.mac = ? AND A.deleted = 0
  3031. ORDER BY A.last_found DESC",
  3032. [$mac_dotted]
  3033. );
  3034. if (!empty($t_login) && isset($t_login['id'])) {
  3035. $user_id = (int)$t_login['id'];
  3036. $auth_id = (int)$t_login['auth_id'];
  3037. $login = htmlspecialchars($t_login['login']);
  3038. $ip = htmlspecialchars($t_login['ip']);
  3039. $result['auth'] = '<a href="/admin/users/edituser.php?id=' . $user_id . '">' . $login . '</a> / ip: <a href="/admin/users/editauth.php?id=' . $auth_id . '">' . $ip . '</a>';
  3040. } else {
  3041. $result['auth'] = 'Unknown';
  3042. }
  3043. $result['mac'] = expand_mac($db, $mac_dotted);
  3044. return $result;
  3045. }
  3046. function get_auth_mac($db, $current_auth)
  3047. {
  3048. if (!isset($current_auth) || $current_auth == 0) {
  3049. return null;
  3050. }
  3051. $t_login = get_record_sql($db,
  3052. "SELECT U.login, A.mac
  3053. FROM user_list AS U, user_auth AS A
  3054. WHERE A.user_id = U.id AND A.id = ?",
  3055. [(int)$current_auth]
  3056. );
  3057. // Исправлена опечатка: было $t_loing, стало $t_login
  3058. if (!empty($t_login) && isset($t_login['login'])) {
  3059. return $t_login['login'] . " [" . $t_login['mac'] . "]";
  3060. }
  3061. return '';
  3062. }
  3063. function add_auth_rule($db, $rule, $type, $user_id)
  3064. {
  3065. $user_id = (int)$user_id;
  3066. $type = (int)$type;
  3067. // Проверяем существование правила
  3068. $auth_rules = get_record_sql($db,
  3069. "SELECT * FROM auth_rules WHERE rule = ? AND rule_type = ?",
  3070. [$rule, $type]
  3071. );
  3072. if (empty($auth_rules)) {
  3073. // Создаём новое правило
  3074. $new = [
  3075. 'user_id' => $user_id,
  3076. 'rule_type' => $type,
  3077. 'rule' => $rule
  3078. ];
  3079. $rule_id = insert_record($db, "auth_rules", $new);
  3080. LOG_INFO($db, "Create auto rule for user_id: " . $user_id . " rule: " . $rule . " rule_type: " . $type);
  3081. } else {
  3082. if ($auth_rules['user_id'] !== $user_id) {
  3083. LOG_WARNING($db, "Create auto rule for user_id: " . $user_id . " rule: " . $rule . " rule_type: " . $type . " failed! Already exists at user_id: " . $auth_rules['user_id']);
  3084. $rule_id = 0;
  3085. } else {
  3086. $rule_id = $auth_rules['id'];
  3087. }
  3088. }
  3089. return $rule_id;
  3090. }
  3091. function update_auth_rule($db, $new, $rule_id = 0)
  3092. {
  3093. if (empty($new) || !isset($new['rule_type']) || !isset($new['rule'])) {
  3094. return 0;
  3095. }
  3096. $rule_id = (int)$rule_id;
  3097. $type = (int)$new['rule_type'];
  3098. $rule = $new['rule'];
  3099. // Проверяем существование другого правила с теми же параметрами
  3100. $auth_rules = get_record_sql($db,
  3101. "SELECT * FROM auth_rules WHERE rule = ? AND rule_type = ? AND id != ?",
  3102. [$rule, $type, $rule_id]
  3103. );
  3104. if (empty($auth_rules)) {
  3105. // Обновляем правило
  3106. $updated_id = update_record($db, "auth_rules", "id = ?", $new, [$rule_id]);
  3107. return $updated_id !== false ? $rule_id : 0;
  3108. } else {
  3109. // Правило уже существует у другого пользователя
  3110. LOG_WARNING($db, "Update auto rule id: " . $rule_id . " rule: " . $rule . " rule_type: " . $type . " failed! Already exists at user_id: " . $auth_rules['user_id']);
  3111. return 0;
  3112. }
  3113. }
  3114. function LOG_INFO($db, $msg, $auth_id = 0)
  3115. {
  3116. if (get_const('log_level') < L_INFO) {
  3117. return;
  3118. }
  3119. write_log($db, $msg, L_INFO, $auth_id);
  3120. }
  3121. function LOG_ERROR($db, $msg, $auth_id = 0)
  3122. {
  3123. if (get_const('log_level') < L_ERROR) {
  3124. return;
  3125. }
  3126. email(L_ERROR,$msg);
  3127. write_log($db, $msg, L_ERROR, $auth_id);
  3128. }
  3129. function LOG_VERBOSE($db, $msg, $auth_id = 0)
  3130. {
  3131. if (get_const('log_level') < L_VERBOSE) {
  3132. return;
  3133. }
  3134. write_log($db, $msg, L_VERBOSE, $auth_id);
  3135. }
  3136. function LOG_WARNING($db, $msg, $auth_id = 0)
  3137. {
  3138. if (get_const('log_level') < L_WARNING) {
  3139. return;
  3140. }
  3141. write_log($db, $msg, L_WARNING, $auth_id);
  3142. }
  3143. function LOG_DEBUG($db, $msg, $auth_id = 0)
  3144. {
  3145. if (!empty(get_const('debug')) and get_const('debug')) {
  3146. write_log($db, $msg, L_DEBUG, $auth_id);
  3147. }
  3148. }
  3149. function truncateByWords($string, $length = 100)
  3150. {
  3151. if (strlen($string) <= $length) {
  3152. return $string;
  3153. }
  3154. $wrapped = wordwrap($string, $length);
  3155. $shortened = substr($wrapped, 0, strpos($wrapped, "\n"));
  3156. return $shortened;
  3157. }
  3158. function get_first_line($msg)
  3159. {
  3160. if (empty($msg)) {
  3161. return;
  3162. }
  3163. preg_match('/(.*)(\n|\<br\>)/', $msg, $matches);
  3164. if (!empty($matches[1])) {
  3165. return $matches[1];
  3166. }
  3167. return truncateByWords($msg, 80);
  3168. }
  3169. function email($level = L_WARNING, $msg = '') {
  3170. if (empty($msg)) { return; }
  3171. // Получаем текущий IP
  3172. $currentIp = null;
  3173. if (!empty($_SESSION['ip'])) {
  3174. $currentIp = filter_var($_SESSION['ip'], FILTER_VALIDATE_IP);
  3175. }
  3176. if (!$currentIp && function_exists('get_client_ip')) {
  3177. $currentIp = filter_var(get_client_ip(), FILTER_VALIDATE_IP);
  3178. }
  3179. $currentIp = $currentIp ?: '127.0.0.1';
  3180. // Получаем текущий логин
  3181. $currentLogin = null;
  3182. if (!empty($_SESSION['login'])) {
  3183. $currentLogin = $_SESSION['login'];
  3184. }
  3185. if (!$currentLogin) {
  3186. $currentLogin = getParam('login', null, null) ?: getParam('api_login', null, null);
  3187. }
  3188. $currentLogin = htmlspecialchars($currentLogin ?: 'http', ENT_QUOTES, 'UTF-8');
  3189. // Обработка сообщения
  3190. $subjectPrefix = ($level === L_WARNING) ? "WARN: " : "ERROR: ";
  3191. $subject = $subjectPrefix . htmlspecialchars(get_first_line($msg), ENT_QUOTES, 'UTF-8') . "...";
  3192. $messageType = ($level === L_WARNING) ? 'WARNING' : 'ERROR';
  3193. // Формирование HTML-сообщения с экранированием
  3194. $safeMsg = nl2br(htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'));
  3195. $htmlMessage = "<html>
  3196. <body>
  3197. <h1>$messageType!</h1>
  3198. <p>Manager: $currentLogin</p>
  3199. <p>From: $currentIp</p>
  3200. <div>$safeMsg</div>
  3201. </body>
  3202. </html>";
  3203. // Заголовки письма
  3204. $senderEmail = filter_var(get_const('sender_email'), FILTER_VALIDATE_EMAIL);
  3205. if (!$senderEmail) {
  3206. error_log("Invalid sender email address");
  3207. return;
  3208. }
  3209. $boundary = md5(uniqid(time(), true));
  3210. $headers = [
  3211. 'From' => $senderEmail,
  3212. 'Reply-To' => $senderEmail,
  3213. 'X-Mailer' => 'PHP',
  3214. 'MIME-Version' => '1.0',
  3215. 'Content-Type' => 'multipart/mixed; boundary=' . $boundary,
  3216. 'Content-Transfer-Encoding' => 'base64'
  3217. ];
  3218. // Формирование тела письма
  3219. $message = "--$boundary\r\n" .
  3220. "Content-Type: text/html; charset=UTF-8\r\n" .
  3221. "Content-Transfer-Encoding: base64\r\n\r\n" .
  3222. chunk_split(base64_encode($htmlMessage)) . "\r\n" .
  3223. "--$boundary--";
  3224. // Отправка письма
  3225. $adminEmail = filter_var(get_const('admin_email'), FILTER_VALIDATE_EMAIL);
  3226. $additional_parameters = "-f ".$senderEmail;
  3227. if ($adminEmail) {
  3228. if (!mail($adminEmail, $subject, $message, $headers, $additional_parameters)) {
  3229. error_log("Failed to send email to $adminEmail");
  3230. }
  3231. } else {
  3232. error_log("Invalid admin email address");
  3233. }
  3234. }
  3235. function write_log($db, $msg, $level = L_INFO, $auth_id = 0)
  3236. {
  3237. if (!isset($msg)) { return; }
  3238. // Получаем текущий IP
  3239. $currentIp = null;
  3240. if (!empty($_SESSION['ip'])) {
  3241. $currentIp = filter_var($_SESSION['ip'], FILTER_VALIDATE_IP);
  3242. }
  3243. if (!$currentIp && function_exists('get_client_ip')) {
  3244. $currentIp = filter_var(get_client_ip(), FILTER_VALIDATE_IP);
  3245. }
  3246. $currentIp = $currentIp ?: '127.0.0.1';
  3247. // Получаем текущий логин
  3248. $currentLogin = null;
  3249. if (!empty($_SESSION['login'])) {
  3250. $currentLogin = $_SESSION['login'];
  3251. }
  3252. if (!$currentLogin) {
  3253. $currentLogin = getParam('login', null, null) ?: getParam('api_login', null, null);
  3254. }
  3255. $currentLogin = htmlspecialchars($currentLogin ?: 'http', ENT_QUOTES, 'UTF-8');
  3256. // Для уровня L_DEBUG пишем в error_log
  3257. if ($level === L_DEBUG) {
  3258. error_log("DEBUG: " . $msg);
  3259. return;
  3260. }
  3261. try {
  3262. // Используем подготовленный запрос PDO напрямую
  3263. $stmt = $db->prepare("INSERT INTO worklog(customer, message, level, auth_id, ip)
  3264. VALUES (:customer, :message, :level, :auth_id, :ip)");
  3265. $result = $stmt->execute([
  3266. ':customer' => $currentLogin,
  3267. ':message' => $msg,
  3268. ':level' => $level,
  3269. ':auth_id' => $auth_id,
  3270. ':ip' => $currentIp
  3271. ]);
  3272. return $result;
  3273. } catch (PDOException $e) {
  3274. // В случае ошибки логируем в error_log, чтобы избежать рекурсии
  3275. error_log("Error writing log to database: " . $e->getMessage());
  3276. return false;
  3277. }
  3278. }
  3279. function print_year_select($year_name, $year)
  3280. {
  3281. print "<select id=\"$year_name\" name=\"$year_name\" >\n";
  3282. for ($i = $year - 10; $i <= $year + 10; $i++) {
  3283. print_select_item($i, $i, $year);
  3284. }
  3285. print "</select>\n";
  3286. }
  3287. function print_date_select($dd, $mm, $yy)
  3288. {
  3289. if ($dd >= 1) {
  3290. print "<b>День</b>\n";
  3291. print "<select id=\"day\" name=\"day\" >\n";
  3292. for ($i = 1; $i <= 31; $i++) {
  3293. print_select_item($i, $i, $dd);
  3294. }
  3295. print "</select>\n";
  3296. }
  3297. if ($mm >= 1) {
  3298. print "<b>Месяц</b>\n";
  3299. print "<select id=\"month\" name=\"month\" >\n";
  3300. for ($i = 1; $i <= 12; $i++) {
  3301. $tmp_date = DateTimeImmutable::createFromFormat('U', strtotime("$i/01/$yy"));
  3302. $month_name = $tmp_date->format('F');
  3303. print_select_item($month_name, $i, $mm);
  3304. }
  3305. print "</select>\n";
  3306. }
  3307. print "<b>Год</b>\n";
  3308. print_year_select('year', $yy);
  3309. }
  3310. function print_date_select2($dd, $mm, $yy)
  3311. {
  3312. if ($dd >= 1) {
  3313. print "<b>День</b>\n";
  3314. print "<select id=\"day2\" name=\"day2\" >\n";
  3315. for ($i = 1; $i <= 31; $i++) {
  3316. print_select_item($i, $i, $dd);
  3317. }
  3318. print "</select>\n";
  3319. }
  3320. if ($mm >= 1) {
  3321. print "<b>Месяц</b>\n";
  3322. print "<select id=\"month2\" name=\"month2\" >\n";
  3323. for ($i = 1; $i <= 12; $i++) {
  3324. $tmp_date = DateTimeImmutable::createFromFormat('U', strtotime("$i/01/$yy"));
  3325. $month_name = $tmp_date->format('F');
  3326. print_select_item($month_name, $i, $mm);
  3327. }
  3328. print "</select>\n";
  3329. }
  3330. print "<b>Год</b>\n";
  3331. print_year_select('year2', $yy);
  3332. }
  3333. function is_up($ip)
  3334. {
  3335. if (!isset($ip) or strlen($ip) == 0) {
  3336. return false;
  3337. }
  3338. exec(sprintf('ping -i .3 -c 1 -W 5 %s', escapeshellarg($ip)), $res, $rval);
  3339. return $rval == 0;
  3340. }
  3341. function apply_device_lock($db, $device_id, $iteration = 0)
  3342. {
  3343. $iteration++;
  3344. if ($iteration > 2) {
  3345. return false;
  3346. }
  3347. // Извлекаем исходную временную метку (без UNIX_TIMESTAMP)
  3348. $dev = get_record_sql($db,
  3349. 'SELECT discovery_locked, locked_timestamp FROM devices WHERE id = ? AND discovery_locked > 0',
  3350. [(int)$device_id]
  3351. );
  3352. // Проверяем, есть ли запись и валидна ли временная метка
  3353. if (empty($dev) || is_empty_datetime($dev['locked_timestamp'])) {
  3354. LOG_DEBUG($db, "Snmp discovery lock not found. Set and discovery.");
  3355. return set_lock_discovery($db, (int)$device_id);
  3356. }
  3357. // Преобразуем строку даты в Unix timestamp
  3358. try {
  3359. // Удаляем микросекунды (если есть, как в PostgreSQL)
  3360. $ts_str = preg_replace('/\.\d+$/', '', $dev['locked_timestamp']);
  3361. $dt = new DateTime($ts_str);
  3362. $u_locked_timestamp = $dt->getTimestamp();
  3363. } catch (Exception $e) {
  3364. // Если парсинг не удался — считаем блокировку недействительной
  3365. LOG_DEBUG($db, "Invalid lock timestamp format. Resetting lock.");
  3366. return set_lock_discovery($db, (int)$device_id);
  3367. }
  3368. $now = time();
  3369. $wait_time = ($u_locked_timestamp + SNMP_LOCK_TIMEOUT) - $now;
  3370. LOG_DEBUG($db, "Check snmp lock for device id: " . $device_id . ". Lock timestamp: " . $u_locked_timestamp . ", now: " . $now);
  3371. if ($wait_time <= 0) {
  3372. LOG_DEBUG($db, "The lock is already expired. Set new lock.");
  3373. return set_lock_discovery($db, (int)$device_id);
  3374. }
  3375. LOG_VERBOSE($db, "Snmp discovery lock for device id: $device_id found! Need wait " . $wait_time . " sec.");
  3376. sleep($wait_time);
  3377. LOG_VERBOSE($db, "Try set new lock and continue discovery for device id: " . $device_id);
  3378. return apply_device_lock($db, (int)$device_id, $iteration);
  3379. }
  3380. function set_lock_discovery($db, $device_id)
  3381. {
  3382. $new['discovery_locked'] = 1;
  3383. $new['locked_timestamp'] = GetNowTimeString();
  3384. if (update_record($db, 'devices', 'id = ?', $new, [(int)$device_id])) {
  3385. return true;
  3386. }
  3387. return false;
  3388. }
  3389. function unset_lock_discovery($db, $device_id)
  3390. {
  3391. $new['discovery_locked'] = 0;
  3392. $new['locked_timestamp'] = GetNowTimeString();
  3393. if (update_record($db, 'devices', 'id = ?', $new, [(int)$device_id])) {
  3394. return true;
  3395. }
  3396. return false;
  3397. }
  3398. function set_port_for_group($db, $group_id, $place_id, $state)
  3399. {
  3400. $group_id = (int)$group_id;
  3401. $place_id = (int)$place_id;
  3402. $state = (int)$state;
  3403. // Получаем список авторизаций для группы
  3404. $auth_list = get_records_sql($db,
  3405. 'SELECT user_auth.id, user_auth.dns_name, user_auth.ip
  3406. FROM user_auth, user_list
  3407. WHERE user_auth.user_id = user_list.id
  3408. AND user_auth.deleted = 0
  3409. AND user_list.ou_id = ?',
  3410. [$group_id]
  3411. );
  3412. LOG_VERBOSE($db, 'Mass port state change started!');
  3413. // Обработка списка авторизаций
  3414. foreach ($auth_list as $row) {
  3415. $auth_id = (int)$row['id'];
  3416. // Формируем фильтр по месту
  3417. if ($place_id == 0) {
  3418. $place_condition = '1=1';
  3419. $place_params = [];
  3420. } else {
  3421. $place_condition = 'D.building_id = ?';
  3422. $place_params = [$place_id];
  3423. }
  3424. // Получение информации об устройстве
  3425. $devSQL = 'SELECT D.id, D.device_name, D.vendor_id, D.device_model, D.ip,
  3426. DP.port, DP.snmp_index
  3427. FROM devices AS D, device_ports AS DP, connections AS C
  3428. WHERE ' . $place_condition . '
  3429. AND D.id = DP.device_id
  3430. AND DP.id = C.port_id
  3431. AND C.auth_id = ?';
  3432. $params = array_merge($place_params, [$auth_id]);
  3433. $dev_info = get_record_sql($db, $devSQL, $params);
  3434. if (empty($dev_info)) {
  3435. continue;
  3436. }
  3437. // Получение устройства
  3438. $device = get_record($db, 'devices', "id = ?", [(int)$dev_info['id']]);
  3439. $snmp = getSnmpAccess($device);
  3440. // Определение режима и обновление nagios_handler
  3441. if ($state == 1) {
  3442. $mode = 'enable';
  3443. update_record($db, 'user_auth',
  3444. 'id = ? AND nagios_handler = ?',
  3445. ['nagios_handler' => 'restart-port'],
  3446. [$auth_id, 'manual-mode']
  3447. );
  3448. } else {
  3449. $mode = 'disable';
  3450. update_record($db, 'user_auth',
  3451. 'id = ? AND nagios_handler = ?',
  3452. ['nagios_handler' => 'manual-mode'],
  3453. [$auth_id, 'restart-port']
  3454. );
  3455. }
  3456. // Логирование
  3457. LOG_INFO($db, "At device " . htmlspecialchars($dev_info['device_name']) .
  3458. " [" . htmlspecialchars($dev_info['ip']) . "] " .
  3459. $mode . " port " . htmlspecialchars($dev_info['port']) .
  3460. " for auth_id: " . $auth_id .
  3461. " (" . htmlspecialchars($row['ip']) . " [" . htmlspecialchars($row['dns_name']) . "])");
  3462. // Установка состояния порта
  3463. set_port_state($dev_info['vendor_id'], $dev_info['snmp_index'],
  3464. $dev_info['ip'], $snmp, $state);
  3465. // Установка состояния PoE
  3466. set_port_poe_state($dev_info['vendor_id'], $dev_info['port'],
  3467. $dev_info['snmp_index'], $dev_info['ip'],
  3468. $snmp, $state);
  3469. }
  3470. LOG_VERBOSE($db, 'Mass port state change stopped.');
  3471. }
  3472. function get_mac_vendor($db, $mac)
  3473. {
  3474. if (empty($mac)) {
  3475. return '';
  3476. }
  3477. $mac = mac_dotted($mac);
  3478. $mac_prefixes = [
  3479. $mac, // полный MAC
  3480. substr($mac, 0, 14), // OUI + 2 байта
  3481. substr($mac, 0, 11), // OUI + 1 байт
  3482. substr($mac, 0, 8) // только OUI
  3483. ];
  3484. $vendor = null;
  3485. foreach ($mac_prefixes as $oui) {
  3486. if (empty($oui)) continue;
  3487. $vendor = get_record_sql($db, 'SELECT companyname,companyaddress FROM mac_vendors WHERE oui = ?', [$oui]);
  3488. if (!empty($vendor)) { break; }
  3489. }
  3490. if (empty($vendor)) { return ''; }
  3491. $address = $vendor['companyaddress'] ?? null;
  3492. $name = $vendor['companyname'] ?? null;
  3493. if (!empty($address)) {
  3494. return $address;
  3495. }
  3496. return $name ?? '';
  3497. }
  3498. function strHexToBin($number)
  3499. {
  3500. $result = '';
  3501. for ($i = 0; $i < strlen($number); $i++) {
  3502. $conv = base_convert($number[$i], 16, 2);
  3503. $result .= str_pad($conv, 4, '0', STR_PAD_LEFT);
  3504. }
  3505. return $result;
  3506. }
  3507. function dec_to_hex($mac)
  3508. {
  3509. if (!isset($mac)) {
  3510. return;
  3511. }
  3512. $mac_array = explode('.', $mac);
  3513. for ($i = 0; $i < count($mac_array); $i++) {
  3514. $hex_i = dechex($mac_array[$i]);
  3515. if (strlen($hex_i) == 1) {
  3516. $hex_i = "0" . $hex_i;
  3517. }
  3518. $mac_array[$i] = $hex_i;
  3519. }
  3520. $hex_mac = implode(':', $mac_array);
  3521. return $hex_mac;
  3522. }
  3523. function mac_simplify($mac)
  3524. {
  3525. if (!isset($mac)) {
  3526. return;
  3527. }
  3528. $mac = strtolower(trim($mac));
  3529. $mac = preg_replace('/(\.|:|-)/', '', $mac);
  3530. return $mac;
  3531. }
  3532. function mac_dotted($mac)
  3533. {
  3534. if (!isset($mac)) {
  3535. return;
  3536. }
  3537. $mac = mac_simplify($mac);
  3538. $mac = preg_replace('/(\S{2})(\S{2})?(\S{2})?(\S{2})?(\S{2})?(\S{2})?/', '$1:$2:$3:$4:$5:$6', $mac);
  3539. $mac = preg_replace('/\:+$/', '', $mac, 5);
  3540. return $mac;
  3541. }
  3542. function unbind_ports($db, $device_id)
  3543. {
  3544. $device_id = (int)$device_id;
  3545. $target = get_records_sql($db,
  3546. "SELECT target_port_id, id FROM device_ports WHERE device_id = ?",
  3547. [$device_id]
  3548. );
  3549. foreach ($target as $row) {
  3550. $port_id = (int)$row['id'];
  3551. $target_port_id = (int)$row['target_port_id'];
  3552. // Обнуляем ссылки на этот порт у других портов
  3553. update_record($db, "device_ports", "target_port_id = ?", ['target_port_id' => 0], [$port_id]);
  3554. // Обнуляем ссылку этого порта на другой порт
  3555. update_record($db, "device_ports", "id = ?", ['target_port_id' => 0], [$port_id]);
  3556. }
  3557. }
  3558. function bind_ports($db, $port_id, $target_id)
  3559. {
  3560. $port_id = (int)$port_id;
  3561. $target_id = (int)$target_id;
  3562. // Отвязываем текущее соединение
  3563. $new = ['target_port_id' => 0];
  3564. $old_target = get_record_sql($db,
  3565. "SELECT target_port_id FROM device_ports WHERE id = ?",
  3566. [$port_id]
  3567. );
  3568. if (!empty($old_target) && !empty($old_target['target_port_id'])) {
  3569. $old_target_id = (int)$old_target['target_port_id'];
  3570. update_record($db, "device_ports", "id = ?", $new, [$old_target_id]);
  3571. }
  3572. // Обнуляем текущий порт
  3573. update_record($db, "device_ports", "id = ?", $new, [$port_id]);
  3574. // Создаём новое соединение
  3575. if ($target_id > 0) {
  3576. // Связываем port_id -> target_id
  3577. update_record($db, "device_ports", "id = ?", ['target_port_id' => $target_id], [$port_id]);
  3578. // Связываем target_id -> port_id
  3579. update_record($db, "device_ports", "id = ?", ['target_port_id' => $port_id], [$target_id]);
  3580. }
  3581. }
  3582. function expand_device_name($db, $name)
  3583. {
  3584. if (empty($name)) {
  3585. return '';
  3586. }
  3587. $device_id = get_device_id($db, $name);
  3588. if (isset($device_id) && $device_id > 0) {
  3589. $safe_name = htmlspecialchars($name);
  3590. $safe_id = (int)$device_id;
  3591. return '<a href="/admin/devices/editdevice.php?id=' . $safe_id . '">' . $safe_name . '</a>';
  3592. }
  3593. return $name;
  3594. }
  3595. function expand_mac($db, $mac)
  3596. {
  3597. if (empty($mac)) {
  3598. return '';
  3599. }
  3600. $mac = mac_dotted($mac);
  3601. $safe_vendor = get_mac_vendor($db, $mac);
  3602. $safe_mac = $mac;
  3603. $safe_url_mac = urlencode($mac);
  3604. if (!empty($safe_vendor)) {
  3605. return '<a href="/admin/logs/mac.php?mac=' . $safe_url_mac . '"><p title="' . $safe_vendor . '">' . $safe_mac . '</p></a>';
  3606. } else {
  3607. return '<a href="/admin/logs/mac.php?mac=' . $safe_url_mac . '">' . $safe_mac . '</a>';
  3608. }
  3609. }
  3610. function expand_log_str($db, $msg)
  3611. {
  3612. if (empty($msg)) {
  3613. return '';
  3614. }
  3615. $result = $msg;
  3616. // === Замена auth_id ===
  3617. $auth_pattern = '/(auth_id:|auth|auth id:|auth id)\s+(\d+)/i';
  3618. $result = preg_replace_callback($auth_pattern, function($matches) {
  3619. $id = (int)$matches[2];
  3620. $safe_id = htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
  3621. return '<a href="/admin/users/editauth.php?id=' . $id . '">auth_id:' . $safe_id . '</a>';
  3622. }, $result);
  3623. // === Замена user_id ===
  3624. $user_pattern = '/(user_id:|user|user id:|user id)\s+(\d+)/i';
  3625. $result = preg_replace_callback($user_pattern, function($matches) {
  3626. $id = (int)$matches[2];
  3627. $safe_id = htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
  3628. return '<a href="/admin/users/edituser.php?id=' . $id . '">user_id:' . $safe_id . '</a>';
  3629. }, $result);
  3630. // === Замена MAC-адресов в формате [1234567890ab] ===
  3631. $mac_pattern1 = '/\s*\[(\w{12})\]\s*/i';
  3632. $result = preg_replace_callback($mac_pattern1, function($matches) {
  3633. $mac_raw = $matches[1];
  3634. $mac_dotted = mac_dotted($mac_raw);
  3635. $safe_mac = htmlspecialchars($mac_dotted, ENT_QUOTES, 'UTF-8');
  3636. $url_mac = urlencode($mac_dotted);
  3637. return ' <a href="/admin/logs/mac.php?mac=' . $url_mac . '">' . $safe_mac . '</a> ';
  3638. }, $result);
  3639. // === Замена MAC-адресов в формате "mac: xx:xx:xx:xx:xx:xx" ===
  3640. $mac_pattern2 = '/\s*mac:\s+([\w:]{17})/i';
  3641. $result = preg_replace_callback($mac_pattern2, function($matches) {
  3642. $mac_raw = $matches[1];
  3643. $mac_dotted = mac_dotted($mac_raw);
  3644. $safe_mac = htmlspecialchars($mac_dotted, ENT_QUOTES, 'UTF-8');
  3645. $url_mac = urlencode($mac_dotted);
  3646. return ' mac: <a href="/admin/logs/mac.php?mac=' . $url_mac . '">' . $safe_mac . '</a> ';
  3647. }, $result);
  3648. // === Замена device name ===
  3649. $device_pattern1 = '/at device\s+([\w.\-]+)/i';
  3650. $result = preg_replace_callback($device_pattern1, function($matches) use ($db) {
  3651. $device_name = $matches[1];
  3652. $device_id = get_device_id($db, $device_name);
  3653. if ($device_id && $device_id > 0) {
  3654. $safe_name = htmlspecialchars($device_name, ENT_QUOTES, 'UTF-8');
  3655. return 'at device <a href="/admin/devices/editdevice.php?id=' . (int)$device_id . '">' . $safe_name . '</a>';
  3656. }
  3657. return $matches[0];
  3658. }, $result);
  3659. // === Замена device_id ===
  3660. $device_pattern2 = '/(device_id:|device id:|device id|device_id)\s+(\d+)/i';
  3661. $result = preg_replace_callback($device_pattern2, function($matches) {
  3662. $id = (int)$matches[2];
  3663. $safe_id = htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
  3664. return 'device_id: <a href="/admin/devices/editdevice.php?id=' . $id . '">' . $safe_id . '</a>';
  3665. }, $result);
  3666. // === Замена IP-адресов ===
  3667. $ip_pattern = '/\s*ip:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*/i';
  3668. $result = preg_replace_callback($ip_pattern, function($matches) use ($db) {
  3669. $ip = $matches[1];
  3670. if (filter_var($ip, FILTER_VALIDATE_IP)) {
  3671. $auth_id = get_auth_by_ip($db, $ip);
  3672. if ($auth_id && $auth_id > 0) {
  3673. $safe_ip = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
  3674. return ' ip: <a href="/admin/users/editauth.php?id=' . (int)$auth_id . '">' . $safe_ip . '</a> ';
  3675. }
  3676. }
  3677. return $matches[0];
  3678. }, $result);
  3679. return $result;
  3680. }
  3681. function is_auth_bind_changed($db, $id, $ip, $mac)
  3682. {
  3683. $old_record = get_record_sql($db,
  3684. "SELECT ip, mac FROM user_auth WHERE id = ?",
  3685. [(int)$id]
  3686. );
  3687. if (empty($old_record) || empty($old_record["ip"]) || empty($old_record["mac"])) {
  3688. return 0;
  3689. }
  3690. if ($old_record["ip"] !== $ip || $old_record["mac"] !== $mac) {
  3691. LOG_VERBOSE($db, "Changed ip or mac for auth record!");
  3692. return 1;
  3693. }
  3694. return 0;
  3695. }
  3696. function copy_auth($db, $id, $new_auth)
  3697. {
  3698. $id = (int)$id;
  3699. $old_record = get_record_sql($db,
  3700. "SELECT * FROM user_auth WHERE id = ?",
  3701. [$id]
  3702. );
  3703. if (empty($old_record)) {
  3704. return null;
  3705. }
  3706. delete_record($db, "user_auth", "id = ?", [$id]);
  3707. $new_auth["user_id"] = $old_record["user_id"];
  3708. $new_auth["changed"] = 1;
  3709. $new_auth["changed_time"] = GetNowTimeString();
  3710. $new_id = insert_record($db, "user_auth", $new_auth);
  3711. if (!empty($new_id)) {
  3712. LOG_VERBOSE($db, "Old record with id: $id deleted. Created new auth record for new ip+mac id: $new_id!");
  3713. }
  3714. return $new_id;
  3715. }
  3716. function get_dns_name($db, $id)
  3717. {
  3718. $auth_record = get_record_sql($db,
  3719. "SELECT dns_name FROM user_auth WHERE id = ?",
  3720. [(int)$id]
  3721. );
  3722. if (!empty($auth_record) && !empty($auth_record['dns_name'])) {
  3723. return $auth_record['dns_name'];
  3724. }
  3725. return '';
  3726. }
  3727. function get_cacti_graph($host_ip, $port_index)
  3728. {
  3729. // Проверка конфигурации Cacti
  3730. if (empty(get_const('cacti_url'))) {
  3731. return null;
  3732. }
  3733. if (empty(CACTI_DB_HOST) || empty(CACTI_DB_USER) || empty(CACTI_DB_PASS) || empty(CACTI_DB_NAME)) {
  3734. return null;
  3735. }
  3736. // Установка соединения с БД Cacti
  3737. $cacti_db_link = new_connection('mysql', CACTI_DB_HOST, CACTI_DB_USER, CACTI_DB_PASS, CACTI_DB_NAME);
  3738. if (!$cacti_db_link) {
  3739. return false;
  3740. }
  3741. // Поиск хоста по IP-адресу
  3742. $cacti_host = get_record_sql($cacti_db_link,
  3743. "SELECT * FROM host WHERE hostname = ?",
  3744. [$host_ip]
  3745. );
  3746. if (empty($cacti_host) || empty($cacti_host["id"])) {
  3747. return null;
  3748. }
  3749. $host_id = (int)$cacti_host["id"];
  3750. $port_index = (string)$port_index; // SNMP index может быть строкой
  3751. // Получение ID шаблонов графиков для трафика интерфейсов
  3752. $traffic_templates = get_records_sql($cacti_db_link,
  3753. "SELECT id FROM graph_templates WHERE name LIKE 'Interface - Traffic%'"
  3754. );
  3755. if (empty($traffic_templates)) {
  3756. return null;
  3757. }
  3758. $template_ids = [];
  3759. foreach ($traffic_templates as $template) {
  3760. $template_ids[] = (int)$template['id'];
  3761. }
  3762. // Формирование условия IN для параметризованного запроса
  3763. $placeholders = str_repeat('?,', count($template_ids) - 1) . '?';
  3764. // Поиск графика по хосту, SNMP-индексу и шаблону
  3765. $cacti_graph = get_record_sql($cacti_db_link,
  3766. "SELECT * FROM graph_local
  3767. WHERE host_id = ?
  3768. AND snmp_index = ?
  3769. AND graph_template_id IN ($placeholders)
  3770. ORDER BY id ASC",
  3771. array_merge([$host_id, $port_index], $template_ids)
  3772. );
  3773. if (empty($cacti_graph) || empty($cacti_graph["id"])) {
  3774. return null;
  3775. }
  3776. $graph_id = (int)$cacti_graph["id"];
  3777. $result = rtrim(get_const('cacti_url'), '/') . "/graph_image.php?local_graph_id=" . $graph_id;
  3778. return $result;
  3779. }
  3780. function print_select_item($description, $value, $current)
  3781. {
  3782. if ((string)$value === (string)$current) {
  3783. print "<option value='" . $value . "' selected>$description</option>";
  3784. } else {
  3785. print "<option value='" . $value . "'>$description</option>";
  3786. }
  3787. }
  3788. function print_select_simple($description, $value)
  3789. {
  3790. print "<option value=$value>$description</option>";
  3791. }
  3792. function print_select_item_ext($description, $value, $current, $disabled)
  3793. {
  3794. if ((string)$value === (string)$current) {
  3795. print "<option value=$value selected>$description</option>";
  3796. } else {
  3797. if (!$disabled) {
  3798. print "<option value=$value>$description</option>";
  3799. } else {
  3800. print "<option disabled value=$value>$description</option>";
  3801. }
  3802. }
  3803. }
  3804. function print_row_at_pages($name, $value)
  3805. {
  3806. print "<select id='" . $name . "' name='" . $name . "'>\n";
  3807. print_select_item(WEB_select_item_more, pow(10, 10), $value);
  3808. print_select_item('25', 25, $value);
  3809. print_select_item('50', 50, $value);
  3810. print_select_item('100', 100, $value);
  3811. print_select_item('200', 200, $value);
  3812. print_select_item('500', 500, $value);
  3813. print_select_item('1000', 1000, $value);
  3814. print_select_item('2000', 2000, $value);
  3815. print "</select>\n";
  3816. }
  3817. function print_navigation($base_url, $page, $displayed, $count_records, $total)
  3818. {
  3819. if ($total <= 1) {
  3820. echo "<div align=left class=records>";
  3821. echo "| Total records: $count_records";
  3822. echo "</div>";
  3823. return;
  3824. }
  3825. // Копируем текущие GET-параметры
  3826. $params = $_GET;
  3827. // Убираем page, чтобы не дублировать
  3828. unset($params['page']);
  3829. // Формируем строку запроса без page
  3830. $query_string = http_build_query($params);
  3831. // Определяем разделитель
  3832. $separator = parse_url($base_url, PHP_URL_QUERY) ? '&' : '?';
  3833. if ($query_string) {
  3834. $url_with_params = $base_url . $separator . $query_string;
  3835. } else {
  3836. $url_with_params = $base_url;
  3837. }
  3838. // Вспомогательная функция для генерации ссылки
  3839. $make_link = function($p) use ($url_with_params, $separator) {
  3840. $page_param = 'page=' . (int)$p;
  3841. if (parse_url($url_with_params, PHP_URL_QUERY)) {
  3842. return $url_with_params . '&' . $page_param;
  3843. } else {
  3844. return $url_with_params . '?' . $page_param;
  3845. }
  3846. };
  3847. // Две назад
  3848. $pagetwoleft = ($page - 2 > 0)
  3849. ? "<a class='first_page_link' href='" . htmlspecialchars($make_link($page - 2)) . "'>" . ($page - 2) . "</a> "
  3850. : '';
  3851. // Одна назад
  3852. $pageoneleft = ($page - 1 > 0)
  3853. ? "<a class='first_page_link' href='" . htmlspecialchars($make_link($page - 1)) . "'>" . ($page - 1) . "</a> "
  3854. : '';
  3855. $pagetemp = ($page - 1 > 0) ? $page - 1 : null;
  3856. // Две вперёд
  3857. $pagetworight = ($page + 2 <= $total)
  3858. ? " <a class='first_page_link' href='" . htmlspecialchars($make_link($page + 2)) . "'>" . ($page + 2) . "</a>"
  3859. : '';
  3860. // Одна вперёд
  3861. $pageoneright = ($page + 1 <= $total)
  3862. ? " <a class='first_page_link' href='" . htmlspecialchars($make_link($page + 1)) . "'>" . ($page + 1) . "</a>"
  3863. : '';
  3864. $pagetemp2 = ($page + 1 <= $total) ? $page + 1 : null;
  3865. // В начало
  3866. $pagerevp = '';
  3867. if ($page != 1 && $pagetemp != 1 && $pagetemp != 2) {
  3868. $pagerevp = "<a href='" . htmlspecialchars($make_link(1)) . "' class='first_page_link' title='В начало'><<</a> ";
  3869. }
  3870. // В конец
  3871. $nextp = '';
  3872. if ($page != $total && $pagetemp2 != ($total - 1) && $pagetemp2 != $total) {
  3873. $nextp = " ... <a href='" . htmlspecialchars($make_link($total)) . "' class='first_page_link'>$total</a>";
  3874. }
  3875. echo "<div align=left class=records>";
  3876. echo $pagerevp . $pagetwoleft . $pageoneleft;
  3877. echo '<span class="num_page_not_link"><b>' . (int)$page . '</b></span>';
  3878. echo $pageoneright . $pagetworight . $nextp;
  3879. echo " | Total records: " . (int)$count_records;
  3880. echo "</div>";
  3881. }
  3882. function get_option($db, $option_id)
  3883. {
  3884. // Валидация входного параметра
  3885. if (!is_numeric($option_id) || $option_id <= 0) {
  3886. return null;
  3887. }
  3888. $sql = "
  3889. SELECT
  3890. COALESCE(c.value, co.default_value) AS value,
  3891. co.option_type
  3892. FROM config_options co
  3893. LEFT JOIN config c ON c.option_id = co.id
  3894. WHERE co.id = ?
  3895. ";
  3896. $record = get_record_sql($db, $sql, [(int)$option_id]);
  3897. if ($record && isset($record['value'])) {
  3898. return $record['value'];
  3899. }
  3900. return null;
  3901. }
  3902. function is_option($db, $option_id)
  3903. {
  3904. if (!is_numeric($option_id) || $option_id <= 0) {
  3905. return false;
  3906. }
  3907. $option = get_record($db, "config", "option_id = ?", [(int)$option_id]);
  3908. if (empty($option) || empty($option['value'])) {
  3909. return false;
  3910. }
  3911. return true;
  3912. }
  3913. function set_option($db, $option_id, $value)
  3914. {
  3915. if (!is_numeric($option_id) || $option_id <= 0) {
  3916. return false;
  3917. }
  3918. $option = ['value' => $value];
  3919. $result = update_record($db, 'config', "option_id = ?", $option, [(int)$option_id]);
  3920. return $result !== false;
  3921. }
  3922. function is_subnet_aton($subnet, $ip)
  3923. {
  3924. if (empty($subnet) || empty($ip)) {
  3925. return false;
  3926. }
  3927. // Проверяем корректность IP-адреса
  3928. if (!is_numeric($ip)) {
  3929. return false;
  3930. }
  3931. $range = cidrToRange($subnet);
  3932. if ($range === false) {
  3933. return false;
  3934. }
  3935. $ip_start = ip2long($range[0]);
  3936. $ip_end = ip2long($range[1]);
  3937. if ($ip_start === false || $ip_end === false) {
  3938. return false;
  3939. }
  3940. if ($ip >= $ip_start && $ip <= $ip_end) {
  3941. return true;
  3942. }
  3943. return false;
  3944. }
  3945. function get_new_user_id($db, $ip, $mac, $hostname)
  3946. {
  3947. $result = [
  3948. 'ip' => $ip,
  3949. 'mac' => !empty($mac) ? mac_dotted($mac) : '',
  3950. 'hostname' => $hostname,
  3951. 'user_id' => null,
  3952. 'ou_id' => null
  3953. ];
  3954. $ip_aton = ip2long($ip);
  3955. if ($ip_aton === false) {
  3956. // Некорректный IP - используем значения по умолчанию
  3957. if (empty($result['ou_id'])) {
  3958. $result['ou_id'] = get_const('default_user_ou_id');
  3959. }
  3960. return $result;
  3961. }
  3962. // Проверка hotspot
  3963. if (is_hotspot($db, $ip)) {
  3964. $result['ou_id'] = get_const('default_hotspot_ou_id');
  3965. return $result;
  3966. }
  3967. // === Правила для пользователей ===
  3968. // IP правила (rule_type = 1)
  3969. if (!empty($ip)) {
  3970. $t_rules = get_records_sql($db,
  3971. "SELECT * FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  3972. );
  3973. foreach ($t_rules as $row) {
  3974. if (!empty($row['rule']) && is_subnet_aton($row['rule'], $ip_aton)) {
  3975. $result['user_id'] = (int)$row['user_id'];
  3976. return $result;
  3977. }
  3978. }
  3979. }
  3980. // MAC правила (rule_type = 2)
  3981. if (!empty($mac)) {
  3982. $mac_simplified = mac_simplify($mac);
  3983. $mac_rules = get_records_sql($db,
  3984. "SELECT * FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  3985. );
  3986. foreach ($mac_rules as $row) {
  3987. if (!empty($row['rule'])) {
  3988. $pattern = '/' . preg_quote(mac_simplify($row['rule']), '/') . '/';
  3989. if (preg_match($pattern, $mac_simplified)) {
  3990. $result['user_id'] = (int)$row['user_id'];
  3991. return $result;
  3992. }
  3993. }
  3994. }
  3995. }
  3996. // Hostname правила (rule_type = 3)
  3997. if (!empty($hostname)) {
  3998. $hostname_rules = get_records_sql($db,
  3999. "SELECT * FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  4000. );
  4001. foreach ($hostname_rules as $row) {
  4002. if (!empty($row['rule'])) {
  4003. // Добавляем делимитеры к регулярному выражению, если их нет
  4004. $pattern = $row['rule'];
  4005. if (@preg_match($pattern, '') === false) {
  4006. // Если шаблон некорректен, пропускаем
  4007. continue;
  4008. }
  4009. if (preg_match($pattern, $hostname)) {
  4010. $result['user_id'] = (int)$row['user_id'];
  4011. return $result;
  4012. }
  4013. }
  4014. }
  4015. }
  4016. // === Правила для OU ===
  4017. // IP правила для OU (rule_type = 1)
  4018. if (!empty($ip)) {
  4019. $t_rules = get_records_sql($db,
  4020. "SELECT * FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  4021. );
  4022. foreach ($t_rules as $row) {
  4023. if (!empty($row['rule']) && is_subnet_aton($row['rule'], $ip_aton)) {
  4024. $result['ou_id'] = (int)$row['ou_id'];
  4025. return $result;
  4026. }
  4027. }
  4028. }
  4029. // MAC правила для OU (rule_type = 2)
  4030. if (!empty($mac)) {
  4031. $mac_simplified = mac_simplify($mac);
  4032. $mac_rules = get_records_sql($db,
  4033. "SELECT * FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  4034. );
  4035. foreach ($mac_rules as $row) {
  4036. if (!empty($row['rule'])) {
  4037. $pattern = '/' . preg_quote(mac_simplify($row['rule']), '/') . '/';
  4038. if (preg_match($pattern, $mac_simplified)) {
  4039. $result['ou_id'] = (int)$row['ou_id'];
  4040. return $result;
  4041. }
  4042. }
  4043. }
  4044. }
  4045. // Hostname правила для OU (rule_type = 3)
  4046. if (!empty($hostname)) {
  4047. $hostname_rules = get_records_sql($db,
  4048. "SELECT * FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  4049. );
  4050. foreach ($hostname_rules as $row) {
  4051. if (!empty($row['rule'])) {
  4052. $pattern = $row['rule'];
  4053. if (@preg_match($pattern, '') === false) {
  4054. continue;
  4055. }
  4056. if (preg_match($pattern, $hostname)) {
  4057. $result['ou_id'] = (int)$row['ou_id'];
  4058. return $result;
  4059. }
  4060. }
  4061. }
  4062. }
  4063. // Значение по умолчанию
  4064. if (empty($result['ou_id'])) {
  4065. $result['ou_id'] = get_const('default_user_ou_id');
  4066. }
  4067. return $result;
  4068. }
  4069. function get_subnet_range($db, $subnet_id)
  4070. {
  4071. if (empty($subnet_id)) {
  4072. return null;
  4073. }
  4074. $t_option = get_record_sql($db,
  4075. "SELECT ip_int_start, ip_int_stop FROM subnets WHERE id = ?",
  4076. [(int)$subnet_id]
  4077. );
  4078. if (empty($t_option)) {
  4079. return null;
  4080. }
  4081. return [
  4082. 'start' => isset($t_option['ip_int_start']) ? (int)$t_option['ip_int_start'] : 0,
  4083. 'stop' => isset($t_option['ip_int_stop']) ? (int)$t_option['ip_int_stop'] : 0
  4084. ];
  4085. }
  4086. function int_between($value, $start, $end)
  4087. {
  4088. return in_array($value, range($start, $end));
  4089. }
  4090. function is_gray_network($ip)
  4091. {
  4092. if (empty($ip)) {
  4093. return 0;
  4094. }
  4095. $ip_aton = ip2long($ip);
  4096. $gray_nets = array('10.0.0.0/8', '192.168.0.0/16', '172.16.0.0/12', '100.64.0.0/10');
  4097. foreach ($gray_nets as &$net) {
  4098. $net_cidr = cidrToRange($net);
  4099. if (int_between($ip_aton, ip2long($net_cidr[0]), ip2long($net_cidr[1]))) {
  4100. return $net;
  4101. }
  4102. }
  4103. return 0;
  4104. }
  4105. function is_hotspot($db, $ip)
  4106. {
  4107. if (empty($ip)) {
  4108. return false;
  4109. }
  4110. $ip_aton = ip2long($ip);
  4111. if ($ip_aton === false) {
  4112. LOG_DEBUG($db, "Invalid IP address: $ip");
  4113. return false;
  4114. }
  4115. LOG_DEBUG($db, "Check hotspot network for ip: $ip");
  4116. $t_option = get_records_sql($db, "SELECT subnet, ip_int_start, ip_int_stop FROM subnets WHERE hotspot = 1");
  4117. foreach ($t_option as $row) {
  4118. if ($ip_aton >= (int)$row['ip_int_start'] && $ip_aton <= (int)$row['ip_int_stop']) {
  4119. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in hotspot network " . $row['subnet'] . ": [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  4120. return true;
  4121. }
  4122. }
  4123. LOG_DEBUG($db, "ip $ip not found in hotspot network!");
  4124. return false;
  4125. }
  4126. function is_office($db, $ip)
  4127. {
  4128. if (empty($ip)) {
  4129. return false;
  4130. }
  4131. $ip_aton = ip2long($ip);
  4132. if ($ip_aton === false) {
  4133. LOG_DEBUG($db, "Invalid IP address: $ip");
  4134. return false;
  4135. }
  4136. LOG_DEBUG($db, "Check office network for ip: $ip");
  4137. $t_option = get_records_sql($db, "SELECT subnet, ip_int_start, ip_int_stop FROM subnets WHERE office = 1");
  4138. foreach ($t_option as $row) {
  4139. if ($ip_aton >= (int)$row['ip_int_start'] && $ip_aton <= (int)$row['ip_int_stop']) {
  4140. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in office network " . $row['subnet'] . ": [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  4141. return true;
  4142. }
  4143. }
  4144. LOG_DEBUG($db, "ip $ip not found in office network!");
  4145. return false;
  4146. }
  4147. function get_office_subnet($db, $ip)
  4148. {
  4149. if (empty($ip)) {
  4150. return null;
  4151. }
  4152. $ip_aton = ip2long($ip);
  4153. if ($ip_aton === false) {
  4154. LOG_DEBUG($db, "Invalid IP address: $ip");
  4155. return null;
  4156. }
  4157. LOG_DEBUG($db, "Check office network for ip: $ip");
  4158. $subnets = get_records_sql($db, 'SELECT * FROM subnets WHERE office = 1');
  4159. foreach ($subnets as $row) {
  4160. if ($ip_aton >= (int)$row['ip_int_start'] && $ip_aton <= (int)$row['ip_int_stop']) {
  4161. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in office {$row['subnet']}: [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  4162. return $row;
  4163. }
  4164. }
  4165. LOG_DEBUG($db, "ip $ip not found in office network!");
  4166. return null;
  4167. }
  4168. function get_notify_subnet($db, $ip)
  4169. {
  4170. if (empty($ip)) {
  4171. return 0;
  4172. }
  4173. $office_subnet = get_office_subnet($db, $ip);
  4174. if ($office_subnet && isset($office_subnet['notify'])) {
  4175. return (int)$office_subnet['notify'];
  4176. }
  4177. return 0;
  4178. }
  4179. function is_our_network($db, $ip)
  4180. {
  4181. if (!isset($ip)) {
  4182. return 0;
  4183. }
  4184. if (is_hotspot($db, $ip)) {
  4185. return 1;
  4186. }
  4187. if (is_office($db, $ip)) {
  4188. return 1;
  4189. }
  4190. return 0;
  4191. }
  4192. function get_const($const_name)
  4193. {
  4194. global $config;
  4195. if (isset($config[$const_name])) {
  4196. return $config[$const_name];
  4197. }
  4198. return NULL;
  4199. }
  4200. function get_eye_version($db)
  4201. {
  4202. $v_table = get_record_sql($db, "SELECT version FROM version");
  4203. if (!empty($v_table)) {
  4204. return $v_table['version'];
  4205. }
  4206. return NULL;
  4207. }
  4208. function getNotifyFlags(): array {
  4209. return [
  4210. WEB_NOTIFY_NONE => NOTIFY_NONE,
  4211. WEB_NOTIFY_CREATE => NOTIFY_CREATE,
  4212. WEB_NOTIFY_UPDATE => NOTIFY_UPDATE,
  4213. WEB_NOTIFY_DELETE => NOTIFY_DELETE,
  4214. ];
  4215. }
  4216. function getNotifyLabels(): array {
  4217. return [
  4218. NOTIFY_NONE => WEB_NOTIFY_NONE,
  4219. NOTIFY_CREATE => WEB_NOTIFY_CREATE,
  4220. NOTIFY_UPDATE => WEB_NOTIFY_UPDATE,
  4221. NOTIFY_DELETE => WEB_NOTIFY_DELETE,
  4222. ];
  4223. }
  4224. function printFlagsByFirstLetter(int $flags): string {
  4225. if ($flags === 0) {
  4226. return 'x';
  4227. }
  4228. $flagLabels = getNotifyLabels();
  4229. $activeLetters = [];
  4230. $fullLabels = [];
  4231. foreach ($flagLabels as $flagValue => $label) {
  4232. if ($flagValue === 0) continue;
  4233. if (($flags & $flagValue) === $flagValue) {
  4234. $firstLetter = mb_substr($label, 0, 1, 'UTF-8');
  4235. $activeLetters[] = $firstLetter;
  4236. $fullLabels[] = $label;
  4237. }
  4238. }
  4239. sort($activeLetters);
  4240. $letters = implode('', $activeLetters);
  4241. $tooltipText = implode(', ', $fullLabels);
  4242. return '<span title="' . htmlspecialchars($tooltipText) . '">' . htmlspecialchars($letters) . '</span>';
  4243. }
  4244. function renderNotifyCombobox(string $name, int $selectedFlags = 0, array $attributes = []): string {
  4245. $labels = getNotifyLabels();
  4246. $flags = getNotifyFlags();
  4247. // Собираем атрибуты
  4248. $attrString = '';
  4249. foreach ($attributes as $key => $value) {
  4250. $attrString .= ' ' . htmlspecialchars($key) . '="' . htmlspecialchars($value) . '"';
  4251. }
  4252. // Предопределенные комбинации с читаемыми названиями
  4253. $combinations = [
  4254. NOTIFY_NONE => $labels[NOTIFY_NONE],
  4255. NOTIFY_CREATE => $labels[NOTIFY_CREATE],
  4256. NOTIFY_UPDATE => $labels[NOTIFY_UPDATE],
  4257. NOTIFY_DELETE => $labels[NOTIFY_DELETE],
  4258. NOTIFY_CREATE | NOTIFY_UPDATE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_UPDATE],
  4259. NOTIFY_CREATE | NOTIFY_DELETE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_DELETE],
  4260. NOTIFY_UPDATE | NOTIFY_DELETE => $labels[NOTIFY_UPDATE] . ' + ' . $labels[NOTIFY_DELETE],
  4261. NOTIFY_CREATE | NOTIFY_UPDATE | NOTIFY_DELETE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_UPDATE] . ' + ' . $labels[NOTIFY_DELETE],
  4262. ];
  4263. $html = '<select name="' . htmlspecialchars($name) . '"' . $attrString . '>';
  4264. foreach ($combinations as $value => $label) {
  4265. $isSelected = ($selectedFlags === $value);
  4266. $selected = $isSelected ? ' selected' : '';
  4267. $html .= '<option value="' . $value . '"' . $selected . '>'
  4268. . htmlspecialchars($label)
  4269. . '</option>';
  4270. }
  4271. $html .= '</select>';
  4272. return $html;
  4273. }
  4274. /**
  4275. * Проверяет, установлен ли флаг создания
  4276. */
  4277. function isNotifyCreate(int $flags): bool {
  4278. return ($flags & NOTIFY_CREATE) === NOTIFY_CREATE;
  4279. }
  4280. /**
  4281. * Проверяет, установлен ли флаг изменения
  4282. */
  4283. function isNotifyUpdate(int $flags): bool {
  4284. return ($flags & NOTIFY_UPDATE) === NOTIFY_UPDATE;
  4285. }
  4286. /**
  4287. * Проверяет, установлен ли флаг удаления
  4288. */
  4289. function isNotifyDelete(int $flags): bool {
  4290. return ($flags & NOTIFY_DELETE) === NOTIFY_DELETE;
  4291. }
  4292. /**
  4293. * Проверяет, отключены ли все уведомления
  4294. */
  4295. function isNotifyNone(int $flags): bool {
  4296. return $flags === NOTIFY_NONE;
  4297. }
  4298. /**
  4299. * Проверяет, установлен ли конкретный флаг
  4300. */
  4301. function hasNotifyFlag(int $flags, int $flagToCheck): bool {
  4302. return ($flags & $flagToCheck) === $flagToCheck;
  4303. }
  4304. /**
  4305. * Устанавливает флаг(и)
  4306. */
  4307. function setNotifyFlag(int &$flags, int $flagToSet): void {
  4308. $flags |= $flagToSet;
  4309. }
  4310. /**
  4311. * Снимает флаг(и)
  4312. */
  4313. function unsetNotifyFlag(int &$flags, int $flagToUnset): void {
  4314. $flags &= ~$flagToUnset;
  4315. }
  4316. /**
  4317. * Преобразует массив выбранных значений в битовую маску
  4318. */
  4319. function arrayToNotifyFlags(array $selectedValues): int {
  4320. $flags = NOTIFY_NONE;
  4321. foreach ($selectedValues as $value) {
  4322. $flags |= (int)$value;
  4323. }
  4324. return $flags;
  4325. }
  4326. /**
  4327. * Проверяет, является ли OU системным (используется по умолчанию для пользователей или хотспотов)
  4328. *
  4329. * @param PDO $db
  4330. * @param int $ou_id
  4331. * @return bool
  4332. */
  4333. function is_system_ou($db, $ou_id = null) {
  4334. if (empty($ou_id) || !is_numeric($ou_id) || $ou_id <= 0) {
  4335. return false;
  4336. }
  4337. $sql = "SELECT 1 FROM ou WHERE id = ? AND (default_users = 1 OR default_hotspot = 1)";
  4338. return !empty(get_record_sql($db, $sql, [$ou_id]));
  4339. }
  4340. $config["org_name"] = get_option($db_link, 32);
  4341. $config["version"] = get_eye_version($db_link);
  4342. $config["KB"] = get_option($db_link, 1);
  4343. if ($config["KB"] == 0) {
  4344. $config["KB"] = 1000;
  4345. }
  4346. if ($config["KB"] == 1) {
  4347. $config["KB"] = 1024;
  4348. }
  4349. $config["debug"] = get_option($db_link, 34);
  4350. $config["log_level"] = get_option($db_link, 53);
  4351. if ($config["debug"]) {
  4352. $config["log_level"] = 255;
  4353. }
  4354. $config["send_email"] = get_option($db_link, 51);
  4355. $config["admin_email"] = get_option($db_link, 21);
  4356. $config["sender_email"] = get_option($db_link, 52);
  4357. $config["snmp_default_version"] = get_option($db_link, 9);
  4358. $config["snmp_default_community"] = get_option($db_link, 11);
  4359. $config["auto_mac_rule"] = get_option($db_link, 64);
  4360. $config["traffic_ipstat_history"] = get_option($db_link, 56);
  4361. $config["cacti_url"] = rtrim(get_option($db_link, 58), '/');
  4362. if (preg_match('/127.0.0.1/', $config["cacti_url"])) {
  4363. $config["cacti_url"] = NULL;
  4364. }
  4365. $config["nagios_url"] = rtrim(get_option($db_link, 57), '/') . '/cgi-bin/';
  4366. if (preg_match('/127.0.0.1/', $config["nagios_url"])) {
  4367. $config["nagios_url"] = NULL;
  4368. }
  4369. $config["torrus_url"] = rtrim(get_option($db_link, 59), '/') . '?nodeid=if//HOST_IP//IF_NAME////inoutbps';
  4370. if (preg_match('/127.0.0.1/', $config["torrus_url"])) {
  4371. $config["torrus_url"] = NULL;
  4372. }
  4373. $config["dns_server"] = get_option($db_link, 3);
  4374. $config["dns_server_type"] = get_option($db_link, 70);
  4375. $ou = get_record_sql($db_link, "SELECT id FROM ou WHERE default_users = 1");
  4376. if (empty($ou)) {
  4377. $config["default_user_ou_id"] = 0;
  4378. } else {
  4379. $config["default_user_ou_id"] = $ou['id'];
  4380. }
  4381. $ou = get_record_sql($db_link, "SELECT id FROM ou WHERE default_hotspot=1");
  4382. if (empty($ou)) {
  4383. $config["default_hotspot_ou_id"] = $config["default_user_ou_id"];
  4384. } else {
  4385. $config["default_hotspot_ou_id"] = $ou['id'];
  4386. }
  4387. $config["init"] = 1;
  4388. clean_dns_cache($db_link);
  4389. //clean_unreferensed_rules($db_link);
  4390. $config["debug"] = 1;