common.php 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151
  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 ou_name";
  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_ipset, '/admin/filters/ipsets.php', $current_page, 0);
  1221. print_submenu_url(WEB_submenu_filter_instances, '/admin/filters/instances.php', $current_page, 1);
  1222. print "</div>\n";
  1223. }
  1224. function print_reports_submenu($current_page)
  1225. {
  1226. print "<div id='submenu'>\n";
  1227. print_submenu_url(WEB_submenu_traffic_ip_report, '/admin/reports/index-full.php', $current_page, 0);
  1228. print_submenu_url(WEB_submenu_traffic_login_report, '/admin/reports/index.php', $current_page, 0);
  1229. print_submenu_url(WEB_submenu_traffic_wan_report, '/admin/reports/wan.php', $current_page, 1);
  1230. print "</div>\n";
  1231. }
  1232. function print_trafdetail_submenu($current_page, $params, $description)
  1233. {
  1234. print "<div id='subsubmenu'>\n";
  1235. print "$description\n";
  1236. print_submenu_url(WEB_submenu_traffic_top10, '/admin/reports/userdaydetail.php' . "?$params", $current_page, 0);
  1237. print_submenu_url(WEB_submenu_detail_log, '/admin/reports/userdaydetaillog.php' . "?$params", $current_page, 1);
  1238. print "</div>\n";
  1239. }
  1240. function print_device_submenu($current_page)
  1241. {
  1242. print "<div id='submenu'>\n";
  1243. print_submenu_url(WEB_submenu_net_devices, '/admin/devices/index.php', $current_page, 0);
  1244. print_submenu_url(WEB_submenu_passive_net_devices, '/admin/devices/index-passive.php', $current_page, 0);
  1245. print_submenu_url(WEB_submenu_hierarchy, '/admin/devices/index-tree.php', $current_page, 0);
  1246. print_submenu_url(WEB_submenu_ports_vlan, '/admin/devices/portsbyvlan.php', $current_page, 1);
  1247. print "</div>\n";
  1248. }
  1249. function open_window_url($url)
  1250. {
  1251. return "window.open('" . $url . "', '_blank');";
  1252. }
  1253. function print_editdevice_submenu($current_page, $id, $dev_type, $dev_name = NULL)
  1254. {
  1255. print "<div id='subsubmenu'>\n";
  1256. $dev_id = '';
  1257. if (isset($id)) {
  1258. $dev_id = '?id=' . $id;
  1259. }
  1260. if (!empty($dev_name)) {
  1261. print "<b>" . $dev_name . "::</b>";
  1262. }
  1263. print_submenu_url(WEB_submenu_options, '/admin/devices/editdevice.php' . $dev_id, $current_page, 0);
  1264. if ($dev_type <= 2) {
  1265. print_submenu_url(WEB_submenu_ports, '/admin/devices/switchport.php' . $dev_id, $current_page, 0);
  1266. print_submenu_url(WEB_submenu_state, '/admin/devices/switchstatus.php' . $dev_id, $current_page, 0);
  1267. print_submenu_url(WEB_submenu_connections, '/admin/devices/switchport-conn.php' . $dev_id, $current_page, 1);
  1268. }
  1269. print "</div>\n";
  1270. }
  1271. function print_ip_submenu($current_page)
  1272. {
  1273. print "<div id='submenu'>\n";
  1274. print_submenu_url(WEB_submenu_ip_list, '/admin/iplist/index.php', $current_page, 0);
  1275. print_submenu_url(WEB_submenu_nagios, '/admin/iplist/nagios.php', $current_page, 0);
  1276. print_submenu_url(WEB_submenu_doubles, '/admin/iplist/doubles.php', $current_page, 0);
  1277. print_submenu_url(WEB_submenu_deleted, '/admin/iplist/deleted.php', $current_page, 0);
  1278. print_submenu_url(WEB_submenu_auto_rules, '/admin/iplist/auto_rules.php', $current_page, 1);
  1279. print "</div>\n";
  1280. }
  1281. function get_nagios_name($auth)
  1282. {
  1283. if (!empty($auth['dns_name'])) {
  1284. return $auth['dns_name'];
  1285. }
  1286. if (!empty($auth['dhcp_hostname'])) {
  1287. return $auth['dhcp_hostname'];
  1288. }
  1289. if (!empty($auth['description'])) {
  1290. $result = transliterate($auth['description']);
  1291. $result = preg_replace('/\(/', '-', $result);
  1292. $result = preg_replace('/\)/', '-', $result);
  1293. $result = preg_replace('/--/', '-', $result);
  1294. return $result;
  1295. }
  1296. if (empty($auth['login'])) {
  1297. $auth['login'] = 'host';
  1298. }
  1299. return $auth['login'] . "_" . $auth['id'];
  1300. }
  1301. function get_ou($db, $ou_value)
  1302. {
  1303. if (!isset($ou_value)) {
  1304. return null;
  1305. }
  1306. $ou_name = get_record_sql($db, "SELECT ou_name FROM ou WHERE id = ?", [(int)$ou_value]);
  1307. if (empty($ou_name)) {
  1308. return null;
  1309. }
  1310. return $ou_name['ou_name'];
  1311. }
  1312. function get_device_model($db, $model_value)
  1313. {
  1314. if (!isset($model_value)) {
  1315. return null;
  1316. }
  1317. $model_name = get_record_sql($db, "SELECT model_name FROM device_models WHERE id = ?", [(int)$model_value]);
  1318. if (empty($model_name)) {
  1319. return null;
  1320. }
  1321. return $model_name['model_name'];
  1322. }
  1323. function get_device_model_name($db, $model_value)
  1324. {
  1325. if (!isset($model_value)) {
  1326. return '';
  1327. }
  1328. $model_name = get_record_sql($db,
  1329. "SELECT M.id, M.model_name, V.name
  1330. FROM device_models M, vendors V
  1331. WHERE M.vendor_id = V.id AND M.id = ?",
  1332. [(int)$model_value]
  1333. );
  1334. if (empty($model_name)) {
  1335. return '';
  1336. }
  1337. return $model_name['name'] . ' ' . $model_name['model_name'];
  1338. }
  1339. function get_device_model_vendor($db, $model_value)
  1340. {
  1341. if (!isset($model_value)) {
  1342. return '';
  1343. }
  1344. $model_name = get_record_sql($db, "SELECT vendor_id FROM device_models WHERE id = ?", [(int)$model_value]);
  1345. if (empty($model_name)) {
  1346. return '';
  1347. }
  1348. return $model_name['vendor_id'];
  1349. }
  1350. function get_building($db, $building_value)
  1351. {
  1352. if (!isset($building_value)) {
  1353. return null;
  1354. }
  1355. $building_name = get_record_sql($db, "SELECT name FROM building WHERE id = ?", [(int)$building_value]);
  1356. if (empty($building_name)) {
  1357. return null;
  1358. }
  1359. return $building_name['name'];
  1360. }
  1361. function print_device_model_select($db, $device_model_name, $device_model_value)
  1362. {
  1363. echo "<select id=\"" . htmlspecialchars($device_model_name) . "\" name=\"" . htmlspecialchars($device_model_name) . "\" class=\"js-select-single\">\n";
  1364. $t_device_model = get_records_sql($db,
  1365. "SELECT M.id, M.model_name, V.name
  1366. FROM device_models M, vendors V
  1367. WHERE M.vendor_id = V.id
  1368. ORDER BY V.name, M.model_name"
  1369. );
  1370. foreach ($t_device_model as $row) {
  1371. $display = htmlspecialchars($row['name']) . " " . htmlspecialchars($row['model_name']);
  1372. print_select_item($display, $row['id'], $device_model_value);
  1373. }
  1374. echo "</select>\n";
  1375. }
  1376. function print_filter_group_select($db, $group_name, $group_value, $disabled = 0)
  1377. {
  1378. $disabled_attr = $disabled ? 'disabled' : '';
  1379. echo "<select id=\"" . htmlspecialchars($group_name) . "\" name=\"" . htmlspecialchars($group_name) . "\" {$disabled_attr}>\n";
  1380. $t_group = get_records_sql($db, "SELECT id, group_name FROM group_list ORDER BY group_name");
  1381. foreach ($t_group as $row) {
  1382. print_select_item(htmlspecialchars($row['group_name']), $row['id'], $group_value);
  1383. }
  1384. echo "</select>\n";
  1385. }
  1386. function print_building_select($db, $building_name, $building_value)
  1387. {
  1388. echo "<select id=\"" . htmlspecialchars($building_name) . "\" name=\"" . htmlspecialchars($building_name) . "\">\n";
  1389. print_select_item(WEB_select_item_all, 0, $building_value);
  1390. $t_building = get_records_sql($db, "SELECT id, name FROM building ORDER BY name");
  1391. foreach ($t_building as $row) {
  1392. print_select_item(htmlspecialchars($row['name']), $row['id'], $building_value);
  1393. }
  1394. echo "</select>\n";
  1395. }
  1396. function print_devmodels_select($db, $devmodel_name, $devmodel_value, $dev_filter = 'device_type<=2')
  1397. {
  1398. // Валидация фильтра для предотвращения SQL-инъекций
  1399. $allowed_filters = [
  1400. 'device_type<=2',
  1401. 'device_type=2',
  1402. 'device_type=1',
  1403. 'device_type=0'
  1404. ];
  1405. if (!in_array($dev_filter, $allowed_filters)) {
  1406. $dev_filter = 'device_type<=2';
  1407. }
  1408. echo "<select id=\"" . htmlspecialchars($devmodel_name) . "\" name=\"" . htmlspecialchars($devmodel_name) . "\">\n";
  1409. print_select_item(WEB_select_item_all, -1, $devmodel_value);
  1410. $t_devmodel = get_records_sql($db,
  1411. "SELECT M.id, V.name, M.model_name
  1412. FROM device_models M, vendors V
  1413. WHERE M.vendor_id = V.id
  1414. AND M.id IN (SELECT device_model_id FROM devices WHERE $dev_filter)
  1415. ORDER BY V.name, M.model_name"
  1416. );
  1417. if (!empty($t_devmodel)) {
  1418. foreach ($t_devmodel as $row) {
  1419. $display = htmlspecialchars($row['name']) . " " . htmlspecialchars($row['model_name']);
  1420. print_select_item($display, $row['id'], $devmodel_value);
  1421. }
  1422. }
  1423. echo "</select>\n";
  1424. }
  1425. function print_devtypes_select($db, $devtype_name, $devtype_value, $mode)
  1426. {
  1427. // Валидация режима для предотвращения SQL-инъекций
  1428. $allowed_modes = [
  1429. '',
  1430. 'device_class = 1',
  1431. 'device_class = 2',
  1432. 'device_class <= 2',
  1433. 'id IN (0,1,2)',
  1434. 'id > 0'
  1435. // Добавьте другие допустимые значения по необходимости
  1436. ];
  1437. if (!in_array($mode, $allowed_modes)) {
  1438. $mode = '';
  1439. }
  1440. echo "<select id=\"" . htmlspecialchars($devtype_name) . "\" name=\"" . htmlspecialchars($devtype_name) . "\">\n";
  1441. print_select_item(WEB_select_item_all, -1, $devtype_value);
  1442. $filter = '';
  1443. if (!empty($mode)) {
  1444. $filter = "WHERE $mode";
  1445. }
  1446. $lang_column = 'name_' . HTML_LANG;
  1447. $t_devtype = get_records_sql($db, "SELECT id, $lang_column FROM device_types $filter ORDER BY $lang_column");
  1448. if (!empty($t_devtype)) {
  1449. foreach ($t_devtype as $row) {
  1450. print_select_item(htmlspecialchars($row[$lang_column]), $row['id'], $devtype_value);
  1451. }
  1452. }
  1453. echo "</select>\n";
  1454. }
  1455. function print_devtype_select($db, $devtype_name, $devtype_value)
  1456. {
  1457. echo "<select id=\"" . htmlspecialchars($devtype_name) . "\" name=\"" . htmlspecialchars($devtype_name) . "\">\n";
  1458. $lang_column = 'name_' . HTML_LANG;
  1459. $t_devtype = get_records_sql($db, "SELECT id, $lang_column FROM device_types ORDER BY $lang_column");
  1460. foreach ($t_devtype as $row) {
  1461. print_select_item(htmlspecialchars($row[$lang_column]), $row['id'], $devtype_value);
  1462. }
  1463. echo "</select>\n";
  1464. }
  1465. function get_group($db, $group_value)
  1466. {
  1467. if (!isset($group_value)) {
  1468. return '';
  1469. }
  1470. $group = get_record_sql($db, "SELECT group_name FROM group_list WHERE id = ?", [(int)$group_value]);
  1471. if (!empty($group) && isset($group['group_name'])) {
  1472. return $group['group_name'];
  1473. }
  1474. return '';
  1475. }
  1476. function get_devtype_name($db, $device_type_id)
  1477. {
  1478. if (!isset($device_type_id)) {
  1479. return '';
  1480. }
  1481. $lang_column = 'name_' . HTML_LANG;
  1482. $type = get_record_sql($db, "SELECT $lang_column FROM device_types WHERE id = ?", [(int)$device_type_id]);
  1483. if (!empty($type) && isset($type[$lang_column])) {
  1484. return $type[$lang_column];
  1485. }
  1486. return '';
  1487. }
  1488. function get_l3_interfaces($db, $device_id)
  1489. {
  1490. $wan = '';
  1491. $lan = '';
  1492. $t_l3int = get_records_sql($db,
  1493. "SELECT name, interface_type FROM device_l3_interfaces WHERE device_id = ? ORDER BY name",
  1494. [(int)$device_id]
  1495. );
  1496. if (empty($t_l3int)) {
  1497. return '';
  1498. }
  1499. foreach ($t_l3int as $row) {
  1500. // Экранируем имя интерфейса для защиты от XSS при выводе
  1501. $name = htmlspecialchars($row['name']);
  1502. if ($row['interface_type'] == 0) {
  1503. $lan .= " " . $name;
  1504. }
  1505. if ($row['interface_type'] == 1) {
  1506. $wan .= " " . $name;
  1507. }
  1508. }
  1509. $wan = trim($wan);
  1510. $lan = trim($lan);
  1511. $result = '';
  1512. if (!empty($wan)) {
  1513. $result .= ' WAN: ' . $wan . '<br>';
  1514. }
  1515. if (!empty($lan)) {
  1516. $result .= ' LAN: ' . $lan;
  1517. }
  1518. return trim($result);
  1519. }
  1520. function get_wan_interfaces($db, $device_id)
  1521. {
  1522. $device_id = (int)$device_id;
  1523. // Получаем WAN-интерфейсы
  1524. $t_l3int = get_records_sql($db,
  1525. "SELECT id, name, snmpin FROM device_l3_interfaces
  1526. WHERE device_id = ? AND interface_type = 1
  1527. ORDER BY name",
  1528. [$device_id]
  1529. );
  1530. // Обрабатываем каждый интерфейс
  1531. foreach ($t_l3int as &$row) {
  1532. $row['description'] = '';
  1533. if (empty($row['snmpin'])) {
  1534. continue;
  1535. }
  1536. // Получаем описание порта
  1537. $conn = get_record_sql($db,
  1538. "SELECT description FROM device_ports
  1539. WHERE device_id = ? AND snmp_index = ?",
  1540. [$device_id, $row['snmpin']]
  1541. );
  1542. // Проверяем, есть ли комментарий в результатах запроса
  1543. if (!empty($conn) && !empty($conn['description'])) {
  1544. $row['description'] = htmlspecialchars($conn['description']);
  1545. }
  1546. }
  1547. unset($row);
  1548. return $t_l3int;
  1549. }
  1550. function get_gw_subnets($db, $device_id)
  1551. {
  1552. $gw_subnets = get_records_sql($db,
  1553. 'SELECT gateway_subnets.*, subnets.subnet, subnets.description
  1554. FROM gateway_subnets
  1555. LEFT JOIN subnets ON gateway_subnets.subnet_id = subnets.id
  1556. WHERE gateway_subnets.device_id = ?
  1557. ORDER BY subnets.subnet ASC',
  1558. [(int)$device_id]
  1559. );
  1560. if (empty($gw_subnets)) {
  1561. return '';
  1562. }
  1563. $result = '';
  1564. foreach ($gw_subnets as $row) {
  1565. if (!empty($row['subnet'])) {
  1566. $result .= ' ' . htmlspecialchars($row['subnet']) . '<br>';
  1567. }
  1568. }
  1569. return trim($result);
  1570. }
  1571. function print_queue_select($db, $queue_name, $queue_value, $disabled = 0)
  1572. {
  1573. $disabled_attr = $disabled ? 'disabled' : '';
  1574. echo "<select id=\"" . htmlspecialchars($queue_name) . "\" name=\"" . htmlspecialchars($queue_name) . "\" {$disabled_attr}>\n";
  1575. $t_queue = get_records_sql($db, "SELECT id, queue_name FROM queue_list ORDER BY queue_name");
  1576. foreach ($t_queue as $row) {
  1577. print_select_item(htmlspecialchars($row['queue_name']), $row['id'], $queue_value);
  1578. }
  1579. echo "</select>\n";
  1580. }
  1581. function get_queue($db, $queue_value)
  1582. {
  1583. if (!isset($queue_value)) {
  1584. return '';
  1585. }
  1586. $queue = get_record_sql($db, "SELECT queue_name FROM queue_list WHERE id = ?", [(int)$queue_value]);
  1587. if (!empty($queue) && isset($queue['queue_name'])) {
  1588. return $queue['queue_name'];
  1589. }
  1590. return '';
  1591. }
  1592. function print_qa_l3int_select($qa_name, $qa_value = 0)
  1593. {
  1594. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1595. print_select_item(WEB_select_item_lan, 0, $qa_value);
  1596. print_select_item(WEB_select_item_wan, 1, $qa_value);
  1597. print "</select>\n";
  1598. }
  1599. function print_qa_rule_select($qa_name, $qa_value = 1)
  1600. {
  1601. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1602. print_select_item('Subnet', 1, $qa_value);
  1603. print_select_item('Mac', 2, $qa_value);
  1604. print_select_item('Hostname', 3, $qa_value);
  1605. print "</select>\n";
  1606. }
  1607. function print_snmp_auth_proto_select($qa_name, $qa_value = 'sha512')
  1608. {
  1609. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1610. print_select_item('sha512', 'sha512', $qa_value);
  1611. print_select_item('sha256', 'sha256', $qa_value);
  1612. print_select_item('sha', 'sha', $qa_value);
  1613. print_select_item('md5', 'md5', $qa_value);
  1614. print "</select>\n";
  1615. }
  1616. function print_snmp_priv_proto_select($qa_name, $qa_value = 'aes128')
  1617. {
  1618. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1619. print_select_item('aes128', 'aes128', $qa_value);
  1620. print_select_item('aes', 'aes', $qa_value);
  1621. print_select_item('des', 'des', $qa_value);
  1622. print "</select>\n";
  1623. }
  1624. function get_int($qa_value = 0)
  1625. {
  1626. if (empty($qa_value)) {
  1627. $qa_value = 0;
  1628. } else {
  1629. $qa_value = (int)$qa_value * 1;
  1630. }
  1631. return $qa_value;
  1632. }
  1633. function print_qa_select($qa_name, $qa_value = 0, $disabled = 0)
  1634. {
  1635. $disabled_attr = $disabled ? 'disabled' : '';
  1636. print "<select name=\"$qa_name\" id=\"$qa_name\" {$disabled_attr}>\n";
  1637. if (empty($qa_value)) {
  1638. $qa_value = 0;
  1639. } else {
  1640. $qa_value = $qa_value * 1;
  1641. }
  1642. print_select_item(WEB_select_item_yes, 1, $qa_value);
  1643. print_select_item(WEB_select_item_no, 0, $qa_value);
  1644. print "</select>\n";
  1645. }
  1646. function print_list_select($qa_name, $qa_value, $list)
  1647. {
  1648. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1649. if (empty($qa_value)) {
  1650. $qa_value = '';
  1651. }
  1652. for ($i = 0; $i < count($list); ++$i) {
  1653. print_select_item($list[$i], $list[$i], $qa_value);
  1654. }
  1655. print "</select>\n";
  1656. }
  1657. function print_qa_select_ext($qa_name, $qa_value = 0, $readonly = 1)
  1658. {
  1659. $state = '';
  1660. if ($readonly) {
  1661. $state = 'disabled=true';
  1662. }
  1663. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1664. print_select_item_ext(WEB_select_item_yes, 1, $qa_value, $readonly);
  1665. print_select_item_ext(WEB_select_item_no, 0, $qa_value, $readonly);
  1666. print "</select>\n";
  1667. }
  1668. function print_td_yes_no($qa_value = 0, $text = FALSE)
  1669. {
  1670. $cl = 'down';
  1671. if ($qa_value == 1) { $cl = 'up'; }
  1672. // $cl = 'data';
  1673. if ($text) {
  1674. print "<td class=\"$cl\">";
  1675. if ($qa_value == 1) { print WEB_select_item_yes; } else { print WEB_select_item_no; }
  1676. print "</td>\n";
  1677. } else { print_td_qa($qa_value,FALSE,$cl); }
  1678. }
  1679. function print_yes_no($qa_value = 0, $yes_style = 'data', $no_style='data')
  1680. {
  1681. if ($qa_value) { $cl = $yes_style; } else { $cl = $no_style; }
  1682. print "<td class=\"$cl\">";
  1683. if ($qa_value == 1) {
  1684. print WEB_select_item_yes;
  1685. } else {
  1686. print WEB_select_item_no;
  1687. }
  1688. print "</td>\n";
  1689. }
  1690. function print_control_proto_select($qa_name, $qa_value = -1)
  1691. {
  1692. print "<select name=\"$qa_name\">\n";
  1693. print_select_item('Disabled', -1, $qa_value);
  1694. print_select_item('Ssh', 0, $qa_value);
  1695. print_select_item('Telnet', 1, $qa_value);
  1696. // print_select_item('Mikrotik rest api', 2, $qa_value);
  1697. print "</select>\n";
  1698. }
  1699. function print_snmp_select($qa_name, $qa_value = 0)
  1700. {
  1701. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1702. print_select_item('Disabled', 0, $qa_value);
  1703. print_select_item('v1', 1, $qa_value);
  1704. print_select_item('v2', 2, $qa_value);
  1705. print_select_item('v3', 3, $qa_value);
  1706. print "</select>\n";
  1707. }
  1708. function print_dhcp_select($qa_name, $qa_value = 0)
  1709. {
  1710. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1711. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1712. $qa_value = 'all';
  1713. }
  1714. print_select_item(WEB_select_item_events, 'all', $qa_value);
  1715. print_select_item(WEB_select_item_lease, 'add', $qa_value);
  1716. print_select_item(WEB_select_item_lease_refresh, 'old', $qa_value);
  1717. print_select_item(WEB_select_item_lease_free, 'del', $qa_value);
  1718. print "</select>\n";
  1719. }
  1720. function print_nagios_handler_select($db, $qa_name)
  1721. {
  1722. $nagios_handler = get_records_sql($db,
  1723. "SELECT DISTINCT nagios_handler FROM user_auth
  1724. WHERE nagios_handler IS NOT NULL AND nagios_handler != '' AND deleted = 0"
  1725. );
  1726. if (!empty($nagios_handler)) {
  1727. echo "<select name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1728. print_select_simple(WEB_select_item_no, '');
  1729. foreach ($nagios_handler as $handler) {
  1730. $value = htmlspecialchars($handler['nagios_handler']);
  1731. print_select_simple($value, $value);
  1732. }
  1733. echo "</select>\n";
  1734. } else {
  1735. echo "<input type=\"text\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"\" size=\"10\" />\n";
  1736. }
  1737. }
  1738. function print_dhcp_acl($db, $qa_name)
  1739. {
  1740. $dhcp_acl = get_records_sql($db,
  1741. "SELECT DISTINCT dhcp_acl FROM user_auth
  1742. WHERE dhcp_acl IS NOT NULL AND dhcp_acl != '' AND deleted = 0"
  1743. );
  1744. if (!empty($dhcp_acl)) {
  1745. echo "<select name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1746. print_select_simple(WEB_select_item_no, '');
  1747. foreach ($dhcp_acl as $acl) {
  1748. $value = htmlspecialchars($acl['dhcp_acl']);
  1749. print_select_simple($value, $value);
  1750. }
  1751. echo "</select>\n";
  1752. } else {
  1753. echo "<input type=\"text\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"\" size=\"10\" />\n";
  1754. }
  1755. }
  1756. function print_dhcp_option_set($db, $qa_name, $disabled = 0)
  1757. {
  1758. $disabled_attr = $disabled ? 'disabled' : '';
  1759. $dhcp_option_sets = get_records_sql($db,
  1760. "SELECT DISTINCT dhcp_option_set FROM user_auth
  1761. WHERE dhcp_option_set IS NOT NULL AND dhcp_option_set != '' AND deleted = 0"
  1762. );
  1763. if (!empty($dhcp_option_sets)) {
  1764. echo "<select name=\"" . htmlspecialchars($qa_name) . "\" {$disabled_attr}>\n";
  1765. print_select_simple(WEB_select_item_no, '');
  1766. foreach ($dhcp_option_sets as $dhcp_option_set) {
  1767. $value = htmlspecialchars($dhcp_option_set['dhcp_option_set']);
  1768. print_select_simple($value, $value);
  1769. }
  1770. echo "</select>\n";
  1771. } else {
  1772. echo "<input type=\"text\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"\" size=\"10\" />\n";
  1773. }
  1774. }
  1775. function print_dhcp_acl_list($db, $qa_name, $value = '', $disabled = 0)
  1776. {
  1777. $disabled_attr = $disabled ? 'disabled' : '';
  1778. $acl_values = [];
  1779. $dhcp_acl = get_records_sql($db,
  1780. "SELECT DISTINCT dhcp_acl FROM user_auth
  1781. WHERE dhcp_acl IS NOT NULL AND dhcp_acl != '' AND deleted = 0"
  1782. );
  1783. // Всегда добавляем 'hotspot-free'
  1784. $acl_values = ['hotspot-free'];
  1785. if (!empty($dhcp_acl)) {
  1786. foreach ($dhcp_acl as $acl) {
  1787. $val = trim($acl['dhcp_acl']);
  1788. if ($val !== '' && $val !== 'hotspot-free') {
  1789. $acl_values[] = $val;
  1790. }
  1791. }
  1792. }
  1793. echo "<input list=\"dhcp_acl\" id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"" . htmlspecialchars($value) . "\" {$disabled_attr}/>";
  1794. echo "<datalist id=\"dhcp_acl\">";
  1795. echo "<option value=\"\">";
  1796. foreach ($acl_values as $acl) {
  1797. echo "<option value=\"" . htmlspecialchars($acl) . "\">";
  1798. }
  1799. echo "</datalist>";
  1800. }
  1801. function print_dhcp_option_set_list($db, $qa_name, $value = '', $disabled = 0)
  1802. {
  1803. $disabled_attr = $disabled ? 'disabled' : '';
  1804. $option_values = [];
  1805. $dhcp_option_sets = get_records_sql($db,
  1806. "SELECT DISTINCT dhcp_option_set FROM user_auth
  1807. WHERE dhcp_option_set IS NOT NULL AND dhcp_option_set != '' AND deleted = 0"
  1808. );
  1809. if (!empty($dhcp_option_sets)) {
  1810. foreach ($dhcp_option_sets as $row) {
  1811. $val = trim($row['dhcp_option_set']);
  1812. if ($val !== '') {
  1813. $option_values[] = $val;
  1814. }
  1815. }
  1816. }
  1817. echo "<input list=\"dhcp_option_set\" id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" value=\"" . htmlspecialchars($value) . "\" {$disabled_attr}/>";
  1818. echo "<datalist id=\"dhcp_option_set\">";
  1819. echo "<option value=\"\">";
  1820. foreach ($option_values as $opt) {
  1821. echo "<option value=\"" . htmlspecialchars($opt) . "\">";
  1822. }
  1823. echo "</datalist>";
  1824. }
  1825. function print_enabled_select($qa_name, $qa_value)
  1826. {
  1827. // Убедимся, что значение корректно
  1828. if (!isset($qa_value) || $qa_value === '') {
  1829. $qa_value = 0;
  1830. } else {
  1831. $qa_value = (int)$qa_value;
  1832. }
  1833. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1834. print_select_item('-', 0, $qa_value);
  1835. print_select_item(WEB_select_item_disabled, 1, $qa_value);
  1836. print_select_item(WEB_select_item_enabled, 2, $qa_value);
  1837. echo "</select>\n";
  1838. }
  1839. function print_rule_target_select($qa_name, $qa_value)
  1840. {
  1841. // Убедимся, что значение корректно
  1842. if (!isset($qa_value) || $qa_value === '') {
  1843. $qa_value = 0;
  1844. } else {
  1845. $qa_value = (int)$qa_value;
  1846. }
  1847. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\">\n";
  1848. print_select_item('-', 0, $qa_value);
  1849. print_select_item(WEB_rules_target_user, 1, $qa_value);
  1850. print_select_item(WEB_rules_target_group, 2, $qa_value);
  1851. echo "</select>\n";
  1852. }
  1853. function print_rule_type_select($qa_name, $qa_value)
  1854. {
  1855. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1856. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1857. $qa_value = 0;
  1858. }
  1859. print_select_item('-', 0, $qa_value);
  1860. print_select_item(WEB_rules_type_subnet, 1, $qa_value);
  1861. print_select_item(WEB_rules_type_mac, 2, $qa_value);
  1862. print_select_item(WEB_rules_type_hostname, 3, $qa_value);
  1863. print "</select>\n";
  1864. }
  1865. function print_yn_select($qa_name, $qa_value)
  1866. {
  1867. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1868. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1869. $qa_value = 0;
  1870. }
  1871. print_select_item('-', 0, $qa_value);
  1872. print_select_item(WEB_select_item_yes, 1, $qa_value);
  1873. print_select_item(WEB_select_item_no, 2, $qa_value);
  1874. print "</select>\n";
  1875. }
  1876. function print_ip_type_select($qa_name, $qa_value)
  1877. {
  1878. print "<select id=\"$qa_name\" name=\"$qa_name\">\n";
  1879. if (!isset($qa_value) or strlen($qa_value) == 0) {
  1880. $qa_value = 0;
  1881. }
  1882. print_select_item(WEB_select_item_every, 0, $qa_value);
  1883. print_select_item(WEB_select_item_static, 1, $qa_value);
  1884. print_select_item(WEB_select_item_dhcp, 2, $qa_value);
  1885. print_select_item(WEB_select_item_suspicious, 3, $qa_value);
  1886. print "</select>\n";
  1887. }
  1888. function print_vendor_select($db, $qa_name, $qa_value, $disabled = 0)
  1889. {
  1890. $disabled_attr = $disabled ? 'disabled' : '';
  1891. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" style=\"width: 100%\" {$disabled_attr}>\n";
  1892. $vendors = get_records_sql($db, "SELECT id, name FROM vendors ORDER BY name");
  1893. print_select_item(WEB_select_item_all, 0, $qa_value);
  1894. foreach ($vendors as $row) {
  1895. print_select_item(htmlspecialchars($row['name']), $row['id'], $qa_value);
  1896. }
  1897. echo "</select>\n";
  1898. }
  1899. function print_vendor_set($db, $qa_name, $qa_value, $disabled = 0)
  1900. {
  1901. $disabled_attr = $disabled ? 'disabled' : '';
  1902. echo "<select id=\"" . htmlspecialchars($qa_name) . "\" name=\"" . htmlspecialchars($qa_name) . "\" style=\"width: 100%\" {$disabled_attr}>\n";
  1903. $vendors = get_records_sql($db, "SELECT id, name FROM vendors ORDER BY name");
  1904. foreach ($vendors as $row) {
  1905. print_select_item(htmlspecialchars($row['name']), $row['id'], $qa_value);
  1906. }
  1907. echo "</select>\n";
  1908. }
  1909. function get_vendor_name($db, $v_id)
  1910. {
  1911. if (!isset($v_id)) {
  1912. return '';
  1913. }
  1914. $vendor = get_record_sql($db, "SELECT name FROM vendors WHERE id = ?", [(int)$v_id]);
  1915. if (!empty($vendor) && isset($vendor['name'])) {
  1916. return $vendor['name'];
  1917. }
  1918. return '';
  1919. }
  1920. function get_qa($qa_value, $text = FALSE)
  1921. {
  1922. if ($text) {
  1923. if ($qa_value == 1) { return "Да"; }
  1924. return "Нет";
  1925. } else {
  1926. if ($qa_value == 1) { return '<span style="font-size: 24px; font-weight: bold;">✓</span>'; }
  1927. return '<span style="font-size: 24px; font-weight: bold;">✗</span>';
  1928. }
  1929. }
  1930. function get_yes($qa_value, $text = FALSE)
  1931. {
  1932. if ($text) {
  1933. if ($qa_value == 1) { return "Да"; }
  1934. return "";
  1935. } else {
  1936. if ($qa_value == 1) { return '<span style="font-size: 16px; font-weight: bold;">✓</span>'; }
  1937. return "";
  1938. }
  1939. }
  1940. function print_td_qa ($qa_value, $text = FALSE, $parent_class = '')
  1941. {
  1942. $cl = "data_green";
  1943. if (!$qa_value) { $cl = "data_red"; }
  1944. print "<td class=\"$parent_class $cl\" >" . get_qa($qa_value,$text) . "</td>";
  1945. }
  1946. function print_td_yes ($qa_value, $text = FALSE, $parent_class = '')
  1947. {
  1948. $cl = "data_green";
  1949. if (!$qa_value) { $cl = "data_red"; }
  1950. print "<td class=\"$parent_class $cl\" >" . get_yes($qa_value,$text) . "</td>";
  1951. }
  1952. function print_action_select($action_name, $action_value)
  1953. {
  1954. print "<select id=\"$action_name\" name=\"$action_name\">\n";
  1955. print_select_item(WEB_select_item_allow, 1, $action_value);
  1956. print_select_item(WEB_select_item_forbidden, 0, $action_value);
  1957. print "</select>\n";
  1958. }
  1959. function get_action($action_value)
  1960. {
  1961. if ($action_value == 1) {
  1962. return "Разрешить";
  1963. }
  1964. return "Запретить";
  1965. }
  1966. function print_filter_select($db, $filter_name, $group_id)
  1967. {
  1968. echo "<select id=\"" . htmlspecialchars($filter_name) . "\" name=\"" . htmlspecialchars($filter_name) . "\" class=\"js-select-single\">\n";
  1969. if (isset($group_id)) {
  1970. $t_filters = get_records_sql($db,
  1971. "SELECT id, name FROM filter_list
  1972. WHERE id NOT IN (SELECT filter_id FROM group_filters WHERE group_id = ?)
  1973. ORDER BY name",
  1974. [(int)$group_id]
  1975. );
  1976. } else {
  1977. $t_filters = get_records_sql($db, "SELECT id, name FROM filter_list ORDER BY name");
  1978. }
  1979. foreach ($t_filters as $row) {
  1980. print_select_item(htmlspecialchars($row['name']), $row['id'], 0);
  1981. }
  1982. echo "</select>\n";
  1983. }
  1984. function get_filter($db, $filter_value)
  1985. {
  1986. if (!isset($filter_value)) {
  1987. return '';
  1988. }
  1989. $filter = get_record_sql($db, "SELECT name FROM filter_list WHERE id = ?", [(int)$filter_value]);
  1990. if (!empty($filter) && isset($filter['name'])) {
  1991. return $filter['name'];
  1992. }
  1993. return '';
  1994. }
  1995. function get_login($db, $user_id)
  1996. {
  1997. if (!isset($user_id)) {
  1998. return '';
  1999. }
  2000. $login = get_record_sql($db, "SELECT login FROM user_list WHERE id = ?", [(int)$user_id]);
  2001. if (!empty($login) && isset($login['login'])) {
  2002. return $login['login'];
  2003. }
  2004. return '';
  2005. }
  2006. function get_auth_count($db, $user_id)
  2007. {
  2008. if (!isset($user_id)) {
  2009. return 0;
  2010. }
  2011. $count = get_record_sql($db, "SELECT COUNT(id) as cnt FROM user_auth WHERE user_id = ? AND deleted = 0", [(int)$user_id]);
  2012. if (!empty($count) && isset($count['cnt'])) {
  2013. return (int)$count['cnt'];
  2014. }
  2015. return 0;
  2016. }
  2017. function print_login_select($db, $login_name, $current_login)
  2018. {
  2019. echo "<select id=\"" . htmlspecialchars($login_name) . "\" name=\"" . htmlspecialchars($login_name) . "\" class=\"js-select-single\">\n";
  2020. $t_login = get_records_sql($db, "SELECT id, login FROM user_list WHERE deleted=0 ORDER BY login");
  2021. print_select_item('None', 0, $current_login);
  2022. foreach ($t_login as $row) {
  2023. print_select_item(htmlspecialchars($row['login']), $row['id'], $current_login);
  2024. }
  2025. echo "</select>\n";
  2026. }
  2027. function print_auth_select($db, $login_name, $current_auth)
  2028. {
  2029. echo "<select id=\"" . htmlspecialchars($login_name) . "\" name=\"" . htmlspecialchars($login_name) . "\" class=\"js-select-single\">\n";
  2030. $params = [];
  2031. $sql = "SELECT U.login, U.description, A.ip, A.id
  2032. FROM user_list AS U, user_auth AS A
  2033. WHERE A.user_id = U.id
  2034. AND A.deleted = 0
  2035. AND (A.id NOT IN (SELECT device_ports.auth_id FROM device_ports) OR A.id = ?)
  2036. ORDER BY U.login, U.description, A.ip";
  2037. $params[] = (int)$current_auth;
  2038. $t_login = get_records_sql($db, $sql, $params);
  2039. print_select_item('Empty', 0, $current_auth);
  2040. foreach ($t_login as $row) {
  2041. $display = htmlspecialchars($row['login']) . "[" . htmlspecialchars($row['description']) . "] - " . htmlspecialchars($row['ip']);
  2042. print_select_item($display, $row['id'], $current_auth);
  2043. }
  2044. echo "</select>\n";
  2045. }
  2046. function print_auth_select_mac($db, $login_name, $current_auth)
  2047. {
  2048. echo "<select id=\"" . htmlspecialchars($login_name) . "\" name=\"" . htmlspecialchars($login_name) . "\" class=\"js-select-single\">\n";
  2049. $params = [];
  2050. $sql = "SELECT U.login, U.description, A.ip, A.mac, A.id
  2051. FROM user_list AS U, user_auth AS A
  2052. WHERE A.user_id = U.id
  2053. AND A.deleted = 0
  2054. AND (A.id NOT IN (SELECT device_ports.auth_id FROM device_ports) OR A.id = ?)
  2055. ORDER BY U.login, U.description, A.ip";
  2056. $params[] = (int)$current_auth;
  2057. $t_login = get_records_sql($db, $sql, $params);
  2058. print_select_item('Empty', 0, $current_auth);
  2059. foreach ($t_login as $row) {
  2060. $display = htmlspecialchars($row['login']) . "[" . htmlspecialchars($row['mac']) . "] - " . htmlspecialchars($row['ip']);
  2061. print_select_item($display, $row['id'], $current_auth);
  2062. }
  2063. echo "</select>\n";
  2064. }
  2065. function compact_port_name($port)
  2066. {
  2067. $result = $port;
  2068. $result = preg_replace('/XGigabitEthernet/', 'X', $result);
  2069. $result = preg_replace('/TenGigabitEthernet/', 'Te', $result);
  2070. $result = preg_replace('/GigabitEthernet/', 'Gi', $result);
  2071. return $result;
  2072. }
  2073. function print_device_port_select($db, $field_name, $device_id, $target_id)
  2074. {
  2075. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2076. $device_id = (int)$device_id;
  2077. $target_id = (int)$target_id;
  2078. $dpSQL = "
  2079. SELECT d.device_name,dp.port,dp.device_id,dp.id,dp.ifname
  2080. FROM devices d
  2081. JOIN device_ports dp
  2082. ON dp.device_id = d.id
  2083. WHERE d.deleted = 0
  2084. AND (dp.device_id <> ? OR dp.id = ?)
  2085. AND NOT EXISTS (
  2086. SELECT 1
  2087. FROM device_ports dp2
  2088. WHERE dp2.target_port_id = dp.id
  2089. AND dp2.target_port_id > 0
  2090. AND dp2.target_port_id <> ?
  2091. )
  2092. ORDER BY d.device_name, dp.port;
  2093. ";
  2094. $t_device = get_records_sql($db,$dpSQL,[$device_id, $target_id, $target_id]);
  2095. print_select_item('Empty', 0, $target_id);
  2096. foreach ($t_device as $row) {
  2097. $ifName = !empty($row['ifname']) ? $row['ifname'] : $row['port'];
  2098. $display = htmlspecialchars($row['device_name']) . "[" . htmlspecialchars($row['port']) . "] - " . htmlspecialchars(compact_port_name($ifName));
  2099. print_select_item($display, $row['id'], $target_id);
  2100. }
  2101. echo "</select>\n";
  2102. }
  2103. function print_device_select($db, $field_name, $device_id)
  2104. {
  2105. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2106. $t_device = get_records_sql($db,
  2107. "SELECT D.device_name, D.id
  2108. FROM devices AS D
  2109. WHERE D.deleted = 0
  2110. ORDER BY D.device_name ASC"
  2111. );
  2112. print_select_item(WEB_select_item_every, 0, $device_id);
  2113. foreach ($t_device as $row) {
  2114. print_select_item(htmlspecialchars($row['device_name']), $row['id'], $device_id);
  2115. }
  2116. echo "</select>\n";
  2117. }
  2118. function print_netdevice_select($db, $field_name, $device_id)
  2119. {
  2120. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2121. $t_device = get_records_sql($db,
  2122. "SELECT D.device_name, D.id
  2123. FROM devices AS D
  2124. WHERE D.deleted = 0 AND D.device_type <= 2
  2125. ORDER BY D.device_name ASC"
  2126. );
  2127. print_select_item(WEB_select_item_every, 0, $device_id);
  2128. foreach ($t_device as $row) {
  2129. print_select_item(htmlspecialchars($row['device_name']), $row['id'], $device_id);
  2130. }
  2131. echo "</select>\n";
  2132. }
  2133. function print_vlan_select($db, $field_name, $vlan)
  2134. {
  2135. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\" style=\"width: 100px;\">\n";
  2136. $v_device = get_records_sql($db, "SELECT DISTINCT vlan FROM device_ports ORDER BY vlan DESC");
  2137. if (!isset($vlan) || empty($vlan)) {
  2138. $vlan = 1;
  2139. }
  2140. print_select_item('1', 1, $vlan);
  2141. foreach ($v_device as $row) {
  2142. if ($row['vlan'] === '1') {
  2143. continue;
  2144. }
  2145. // VLAN-ы обычно числовые, но на всякий случай экранируем
  2146. $vlan_val = htmlspecialchars($row['vlan']);
  2147. print_select_item($vlan_val, $vlan_val, $vlan);
  2148. }
  2149. echo "</select>\n";
  2150. }
  2151. function print_device_select_ip($db, $field_name, $device_ip)
  2152. {
  2153. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2154. $t_device = get_records_sql($db,
  2155. "SELECT D.device_name, D.ip
  2156. FROM devices AS D
  2157. WHERE D.deleted = 0
  2158. ORDER BY D.device_name ASC"
  2159. );
  2160. print_select_item(WEB_select_item_every, '', $device_ip);
  2161. foreach ($t_device as $row) {
  2162. $display = htmlspecialchars($row['device_name']);
  2163. $value = htmlspecialchars($row['ip']); // IP безопасен, но для единообразия
  2164. print_select_item($display, $value, $device_ip);
  2165. }
  2166. echo "</select>\n";
  2167. }
  2168. function print_syslog_device_select($db, $field_name, $syslog_filter, $device_ip)
  2169. {
  2170. // Валидация фильтра для предотвращения SQL-инъекций
  2171. $allowed_filters = [
  2172. 'facility = 1',
  2173. 'facility = 2',
  2174. 'priority <= 3',
  2175. 'message LIKE "%error%"',
  2176. 'message LIKE "%warning%"',
  2177. '1=1' // для случая "все записи"
  2178. // Добавьте другие допустимые значения по необходимости
  2179. ];
  2180. if (!in_array($syslog_filter, $allowed_filters)) {
  2181. $syslog_filter = '1=1';
  2182. }
  2183. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\" class=\"js-select-single\">\n";
  2184. $t_device = get_records_sql($db,
  2185. "SELECT R.ip, D.device_name
  2186. FROM (SELECT DISTINCT ip FROM remote_syslog WHERE $syslog_filter) AS R
  2187. LEFT JOIN (SELECT ip, device_name FROM devices WHERE deleted = 0) AS D ON R.ip = D.ip
  2188. ORDER BY R.ip ASC"
  2189. );
  2190. print_select_item(WEB_select_item_every, '', $device_ip);
  2191. foreach ($t_device as $row) {
  2192. $display_name = !empty($row['device_name']) ? $row['device_name'] : $row['ip'];
  2193. $display = htmlspecialchars($display_name);
  2194. $value = htmlspecialchars($row['ip']);
  2195. print_select_item($display, $value, $device_ip);
  2196. }
  2197. echo "</select>\n";
  2198. }
  2199. function print_gateway_select($db, $field_name, $device_id)
  2200. {
  2201. echo "<select id=\"" . htmlspecialchars($field_name) . "\" name=\"" . htmlspecialchars($field_name) . "\">\n";
  2202. $t_device = get_records_sql($db,
  2203. "SELECT D.device_name, D.id
  2204. FROM devices AS D
  2205. WHERE D.deleted = 0 AND D.device_type = 2
  2206. ORDER BY D.device_name ASC"
  2207. );
  2208. print_select_item(WEB_select_item_every, 0, $device_id);
  2209. foreach ($t_device as $row) {
  2210. print_select_item(htmlspecialchars($row['device_name']), $row['id'], $device_id);
  2211. }
  2212. echo "</select>\n";
  2213. }
  2214. function get_gateways($db)
  2215. {
  2216. $t_device = get_records_sql($db,
  2217. "SELECT D.device_name, D.id
  2218. FROM devices AS D
  2219. WHERE D.deleted = 0 AND D.device_type = 2
  2220. ORDER BY D.device_name ASC"
  2221. );
  2222. $result = [];
  2223. foreach ($t_device as $row) {
  2224. $result[$row['id']] = $row['device_name'];
  2225. }
  2226. return $result;
  2227. }
  2228. function print_device_port($db, $target_id)
  2229. {
  2230. $t_device = get_records_sql($db,
  2231. "SELECT D.device_name, DP.port, DP.device_id
  2232. FROM devices AS D, device_ports AS DP
  2233. WHERE D.id = DP.device_id AND DP.id = ? AND D.deleted = 0",
  2234. [(int)$target_id]
  2235. );
  2236. foreach ($t_device as $row) {
  2237. $device_name = htmlspecialchars($row['device_name']);
  2238. $port = htmlspecialchars($row['port']);
  2239. $device_id = (int)$row['device_id'];
  2240. echo "<a href=\"/admin/devices/switchport.php?id={$device_id}\">{$device_name}[{$port}]</a>\n";
  2241. }
  2242. }
  2243. function get_device_ips($db, $device_id)
  2244. {
  2245. $switch = get_record($db, 'devices', 'id = ?', [(int)$device_id]);
  2246. $result = [];
  2247. if (!empty($switch['user_id'])) {
  2248. $auth_ips = get_records($db, 'user_auth', 'deleted = 0 AND user_id = ?', [(int)$switch['user_id']]);
  2249. foreach ($auth_ips as $value) {
  2250. if (isset($value['ip'])) {
  2251. $result[] = $value['ip'];
  2252. }
  2253. }
  2254. } else {
  2255. if (isset($switch['ip'])) {
  2256. $result[] = $switch['ip'];
  2257. }
  2258. }
  2259. return $result;
  2260. }
  2261. function get_device_id($db, $device_name)
  2262. {
  2263. if (empty($device_name)) {
  2264. return null;
  2265. }
  2266. $dev = get_record_sql($db,
  2267. "SELECT id FROM devices WHERE device_name = ? AND deleted = 0",
  2268. [$device_name]
  2269. );
  2270. if (empty($dev)) {
  2271. return null;
  2272. }
  2273. return $dev["id"];
  2274. }
  2275. function get_device_name($db, $device_id)
  2276. {
  2277. if (!isset($device_id)) {
  2278. return null;
  2279. }
  2280. $dev = get_record_sql($db,
  2281. "SELECT device_name FROM devices WHERE id = ?",
  2282. [(int)$device_id]
  2283. );
  2284. if (empty($dev)) {
  2285. return null;
  2286. }
  2287. return $dev["device_name"];
  2288. }
  2289. function get_auth_by_ip($db, $ip)
  2290. {
  2291. if (empty($ip)) {
  2292. return null;
  2293. }
  2294. $auth = get_record_sql($db,
  2295. "SELECT id FROM user_auth WHERE ip = ? AND deleted = 0",
  2296. [$ip]
  2297. );
  2298. if (empty($auth)) {
  2299. return null;
  2300. }
  2301. return $auth["id"];
  2302. }
  2303. function get_user_by_ip($db, $ip)
  2304. {
  2305. if (empty($ip)) {
  2306. return null;
  2307. }
  2308. $auth = get_record_sql($db,
  2309. "SELECT user_id FROM user_auth WHERE ip = ? AND deleted = 0",
  2310. [$ip]
  2311. );
  2312. if (empty($auth)) {
  2313. return null;
  2314. }
  2315. return $auth["user_id"];
  2316. }
  2317. function get_device_by_auth($db, $id)
  2318. {
  2319. if (!isset($id)) {
  2320. return null;
  2321. }
  2322. $f_dev = get_record_sql($db,
  2323. "SELECT id FROM devices WHERE user_id = ? AND deleted = 0",
  2324. [(int)$id]
  2325. );
  2326. if (empty($f_dev)) {
  2327. return null;
  2328. }
  2329. return $f_dev['id'];
  2330. }
  2331. function print_auth_port($db, $port_id, $new_window = false)
  2332. {
  2333. $t_auth = get_records_sql($db,
  2334. "SELECT A.ip, A.ip_int, A.mac, A.id, A.dns_name, A.user_id
  2335. FROM user_auth AS A, connections AS C
  2336. WHERE C.port_id = ? AND A.id = C.auth_id AND A.deleted = 0
  2337. ORDER BY A.ip_int",
  2338. [(int)$port_id]
  2339. );
  2340. foreach ($t_auth as $row) {
  2341. // Определяем отображаемое имя
  2342. $name = !empty($row['dns_name']) ? $row['dns_name'] : $row['ip'];
  2343. // Формируем title
  2344. $login = get_login($db, $row['user_id']);
  2345. $title = htmlspecialchars($login) . " =>" . htmlspecialchars($row['ip']) . "[" . htmlspecialchars($row['mac']) . "]";
  2346. if (!empty($row['dns_name'])) {
  2347. $title .= " | " . htmlspecialchars($row['dns_name']);
  2348. }
  2349. // Экранируем данные для вывода
  2350. $display_name = htmlspecialchars($name);
  2351. $display_ip = htmlspecialchars($row['ip']);
  2352. $auth_id = (int)$row['id'];
  2353. if ($new_window) {
  2354. $url = "/admin/users/editauth.php?id=" . $auth_id;
  2355. echo "<a href=\"\" title=\"" . $title . "\" onclick=\"" . open_window_url($url) . " return false;\">" . $display_name . " [" . $display_ip . "]</a><br>\n";
  2356. } else {
  2357. echo "<a href=\"/admin/users/editauth.php?id=" . $auth_id . "\" title=\"" . $title . "\">" . $display_name . " [" . $display_ip . "]</a><br>\n";
  2358. }
  2359. }
  2360. }
  2361. function get_port_description($db, $port_id, $port_description = '')
  2362. {
  2363. $t_auth = get_records_sql($db,
  2364. "SELECT A.ip_int, A.description
  2365. FROM user_auth AS A, connections AS C
  2366. WHERE C.port_id = ? AND A.id = C.auth_id AND A.deleted = 0
  2367. ORDER BY A.ip_int",
  2368. [(int)$port_id]
  2369. );
  2370. $description_found = false;
  2371. $result = '';
  2372. foreach ($t_auth as $row) {
  2373. $desc = !empty($row['description']) ? $row['description'] : '';
  2374. if (!empty($desc)) {
  2375. $description_found = true;
  2376. }
  2377. $result .= $desc . '<br>';
  2378. }
  2379. if (!$description_found) {
  2380. return $port_description;
  2381. }
  2382. if (!empty($port_description)) {
  2383. $result .= '(' . $port_description . ')';
  2384. }
  2385. return $result;
  2386. }
  2387. function print_auth_simple($db, $auth_id)
  2388. {
  2389. $auth = get_record($db, "user_auth", "id = ?", [(int)$auth_id]);
  2390. if (empty($auth)) {
  2391. return;
  2392. }
  2393. // Определяем отображаемое имя
  2394. $name = !empty($auth['dns_name']) ? $auth['dns_name'] :
  2395. (!empty($auth['description']) ? $auth['description'] : $auth['ip']);
  2396. $display_name = $name;
  2397. $safe_auth_id = (int)$auth_id;
  2398. echo "<a href=\"/admin/users/editauth.php?id={$safe_auth_id}\">{$display_name}</a><br>\n";
  2399. }
  2400. function print_auth($db, $auth_id)
  2401. {
  2402. $auth = get_record($db, "user_auth", "id = ?", [(int)$auth_id]);
  2403. if (empty($auth)) {
  2404. return;
  2405. }
  2406. // Формируем отображаемое имя
  2407. if (!empty($auth['dns_name'])) {
  2408. $name = $auth['dns_name'];
  2409. if (!empty($auth['description'])) {
  2410. $name .= " (" . $auth['description'] . ")";
  2411. }
  2412. } else {
  2413. $name = !empty($auth['description']) ? $auth['description'] : $auth['ip'];
  2414. }
  2415. if (!empty($name) && !empty($auth['ip'])) {
  2416. $name .= " [" . $auth['ip'] . "]";
  2417. }
  2418. $display_name = htmlspecialchars($name);
  2419. $safe_auth_id = (int)$auth_id;
  2420. echo "<a href=\"/admin/users/editauth.php?id={$safe_auth_id}\">{$display_name}</a><br>\n";
  2421. }
  2422. function print_auth_detail($db, $auth_id)
  2423. {
  2424. $auth = get_record($db, "user_auth", "id = ?", [(int)$auth_id]);
  2425. if (empty($auth)) {
  2426. return;
  2427. }
  2428. // Формируем отображаемое имя
  2429. if (!empty($auth['dns_name'])) {
  2430. $name = $auth['dns_name'];
  2431. if (!empty($auth['description'])) {
  2432. $name .= " (" . $auth['description'] . ")";
  2433. }
  2434. } else {
  2435. $name = !empty($auth['description']) ? $auth['description'] : $auth['ip'];
  2436. }
  2437. if (!empty($name) && !empty($auth['ip'])) {
  2438. $name .= " [" . $auth['ip'] . "]";
  2439. }
  2440. // Добавляем информацию о последнем обнаружении
  2441. if (!empty($auth['last_found'])) {
  2442. $name .= " last: [" . $auth['last_found'] . "] ";
  2443. }
  2444. // Добавляем статус удаления
  2445. if ($auth['deleted'] == 1) {
  2446. $name .= " <font color='red'>DELETED!!!</font>";
  2447. }
  2448. $display_name = htmlspecialchars($name);
  2449. $safe_auth_id = (int)$auth_id;
  2450. echo "<a href=\"/admin/users/editauth.php?id={$safe_auth_id}\">{$display_name}</a><br>\n";
  2451. }
  2452. function get_auth_port_count($db, $port_id)
  2453. {
  2454. $t_device = get_record_sql($db,
  2455. "SELECT COUNT(A.id) as cnt
  2456. FROM user_auth AS A, connections AS C
  2457. WHERE C.port_id = ? AND A.id = C.auth_id AND A.deleted = 0",
  2458. [(int)$port_id]
  2459. );
  2460. if (empty($t_device)) {
  2461. return 0;
  2462. }
  2463. return (int)$t_device['cnt'];
  2464. }
  2465. function get_connection($db, $auth_id)
  2466. {
  2467. $t_device = get_record_sql($db,
  2468. "SELECT D.device_name, DP.port
  2469. FROM devices AS D, device_ports AS DP, connections AS C
  2470. WHERE D.deleted = 0 AND D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id = ?",
  2471. [(int)$auth_id]
  2472. );
  2473. if (!empty($t_device) && isset($t_device['device_name'])) {
  2474. $device_name = expand_device_name($db, $t_device['device_name']);
  2475. $port = $t_device['port'];
  2476. return $device_name . "[" . $port . "]";
  2477. }
  2478. return '';
  2479. }
  2480. function get_connection_string($db, $auth_id)
  2481. {
  2482. $t_device = get_record_sql($db,
  2483. "SELECT D.device_name, DP.port
  2484. FROM devices AS D, device_ports AS DP, connections AS C
  2485. WHERE D.deleted = 0 AND D.id = DP.device_id AND DP.id = C.port_id AND C.auth_id = ?",
  2486. [(int)$auth_id]
  2487. );
  2488. if (!empty($t_device) && isset($t_device['device_name'])) {
  2489. return $t_device['device_name'] . "[" . $t_device['port'] . "]";
  2490. }
  2491. return '';
  2492. }
  2493. function get_port($db, $port_id)
  2494. {
  2495. $t_device = get_record_sql($db,
  2496. "SELECT D.device_name, DP.port
  2497. FROM devices AS D, device_ports AS DP
  2498. WHERE D.deleted = 0 AND D.id = DP.device_id AND DP.id = ?",
  2499. [(int)$port_id]
  2500. );
  2501. if (!empty($t_device) && isset($t_device['device_name'])) {
  2502. $device_name = expand_device_name($db, $t_device['device_name']);
  2503. return $device_name . "[" . $t_device['port'] . "]";
  2504. }
  2505. return '';
  2506. }
  2507. function print_option_select($db, $option_name)
  2508. {
  2509. echo "<select id=\"" . htmlspecialchars($option_name) . "\" name=\"" . htmlspecialchars($option_name) . "\">\n";
  2510. // Неуникальные опции
  2511. $t_option = get_records_sql($db,
  2512. "SELECT id, option_name FROM config_options
  2513. WHERE uniq = 0 AND draft = 0 AND id != 68
  2514. ORDER BY option_name"
  2515. );
  2516. if (!empty($t_option)) {
  2517. foreach ($t_option as $row) {
  2518. echo "<option value=\"" . (int)$row['id'] . "\">" . htmlspecialchars($row['option_name']) . "</option>\n";
  2519. }
  2520. }
  2521. // Уникальные опции (которые ещё не используются)
  2522. $t_option = get_records_sql($db,
  2523. "SELECT id, option_name FROM config_options
  2524. WHERE draft = 0 AND uniq = 1 AND id != 68 AND id NOT IN (SELECT option_id FROM config WHERE draft = 0)
  2525. ORDER BY option_name"
  2526. );
  2527. if (!empty($t_option)) {
  2528. foreach ($t_option as $row) {
  2529. echo "<option value=\"" . (int)$row['id'] . "\">" . htmlspecialchars($row['option_name']) . "</option>\n";
  2530. }
  2531. }
  2532. echo "</select>\n";
  2533. }
  2534. function ResolveIP($db, $ip_int)
  2535. {
  2536. $ip_name = "-";
  2537. if (empty($ip_int)) {
  2538. return $ip_name;
  2539. }
  2540. // Проверяем кэш
  2541. $dns_cache = get_record_sql($db, "SELECT dns FROM dns_cache WHERE ip = ?", [(int)$ip_int]);
  2542. if (empty($dns_cache) || empty($dns_cache['dns'])) {
  2543. $ip_str = long2ip((int)$ip_int);
  2544. $ip_name = gethostbyaddr($ip_str);
  2545. // Проверяем результат разрешения
  2546. if (empty($ip_name) || $ip_name == $ip_str) {
  2547. $ip_name = "-";
  2548. }
  2549. // Сохраняем в кэш
  2550. run_sql($db, "INSERT INTO dns_cache(dns, ip) VALUES(?, ?)", [$ip_name, (int)$ip_int]);
  2551. } else {
  2552. $ip_name = $dns_cache['dns'];
  2553. }
  2554. return $ip_name;
  2555. }
  2556. function clean_dns_cache($db)
  2557. {
  2558. $date = time() - 86400; // 24 часа назад
  2559. $clean_date = date('Y-m-d H:i:s', $date);
  2560. run_sql($db, "DELETE FROM dns_cache WHERE ts <= ?", [$clean_date]);
  2561. }
  2562. function clean_unreferensed_rules($db)
  2563. {
  2564. run_sql($db, "DELETE FROM auth_rules WHERE user_id NOT IN (SELECT id FROM user_list)");
  2565. }
  2566. function FormatDateStr($format = 'Y-m-d H:i:s', $date_str)
  2567. {
  2568. $date1 = GetDateTimeFromString($date_str);
  2569. $result = $date1->format($format);
  2570. return $result;
  2571. }
  2572. function GetDateTimeFromString($date_str)
  2573. {
  2574. if (!is_a($date_str, 'DateTime')) {
  2575. $t_date_str = urldecode($date_str);
  2576. $t_date_str = preg_replace('/(\'|\")/', '', $t_date_str);
  2577. $t_date_str = preg_replace('/T/', ' ', $t_date_str);
  2578. $date1 = DateTime::createFromFormat('Y-m-d H:i:s', $t_date_str);
  2579. if (!$date1) {
  2580. $date1 = DateTime::createFromFormat('Y.m.d H:i:s', $t_date_str);
  2581. }
  2582. if (!$date1) {
  2583. $date1 = DateTime::createFromFormat('Y/m/d H:i:s', $t_date_str);
  2584. }
  2585. if (!$date1) {
  2586. $date1 = DateTime::createFromFormat('Y-m-d H:i', $t_date_str);
  2587. }
  2588. if (!$date1) {
  2589. $date1 = DateTime::createFromFormat('Y.m.d H:i', $t_date_str);
  2590. }
  2591. if (!$date1) {
  2592. $date1 = DateTime::createFromFormat('Y/m/d H:i', $t_date_str);
  2593. }
  2594. if (!$date1) {
  2595. $date1 = DateTime::createFromFormat('Y-m-d|', $t_date_str);
  2596. }
  2597. if (!$date1) {
  2598. $date1 = DateTime::createFromFormat('Y.m.d|', $t_date_str);
  2599. }
  2600. if (!$date1) {
  2601. $date1 = DateTime::createFromFormat('Y/m/d|', $t_date_str);
  2602. }
  2603. if (!$date1) {
  2604. $date1 = new DateTime;
  2605. $date1->setTime(0, 0, 0, 1);
  2606. }
  2607. } else {
  2608. return $date_str;
  2609. }
  2610. return $date1;
  2611. }
  2612. function GetNowTimeString()
  2613. {
  2614. $now = new DateTimeImmutable('now');
  2615. $result = $now->format('Y-m-d H:i:s');
  2616. return $result;
  2617. }
  2618. function GetNowDayString()
  2619. {
  2620. $now = new DateTimeImmutable('now');
  2621. $result = $now->format('Y-m-d');
  2622. return $result;
  2623. }
  2624. function get_ip_subnet($db, $ip)
  2625. {
  2626. if (empty($ip)) {
  2627. return null;
  2628. }
  2629. $ip_aton = ip2long($ip);
  2630. if ($ip_aton === false) {
  2631. return null;
  2632. }
  2633. // Исправлено: добавлены скобки для правильного порядка операций
  2634. $user_subnet = get_record_sql($db,
  2635. "SELECT * FROM subnets
  2636. WHERE (hotspot = 1 OR office = 1)
  2637. AND ? >= ip_int_start
  2638. AND ? <= ip_int_stop",
  2639. [$ip_aton, $ip_aton]
  2640. );
  2641. if (empty($user_subnet)) {
  2642. return null;
  2643. }
  2644. return $user_subnet;
  2645. }
  2646. function find_mac_in_subnet($db, $ip, $mac)
  2647. {
  2648. if (empty($ip) || empty($mac)) {
  2649. return null;
  2650. }
  2651. $ip_subnet = get_ip_subnet($db, $ip);
  2652. if (empty($ip_subnet)) {
  2653. return null;
  2654. }
  2655. $t_auth = get_records_sql($db,
  2656. "SELECT id, mac, user_id
  2657. FROM user_auth
  2658. WHERE ip_int >= ?
  2659. AND ip_int <= ?
  2660. AND mac = ?
  2661. AND deleted = 0
  2662. ORDER BY id",
  2663. [$ip_subnet['ip_int_start'], $ip_subnet['ip_int_stop'], $mac]
  2664. );
  2665. if (empty($t_auth)) {
  2666. return ['count' => 0, 'users_id' => []];
  2667. }
  2668. $result = ['count' => 0, 'users_id' => []];
  2669. foreach ($t_auth as $row) {
  2670. if (!empty($row['id'])) {
  2671. $result['count']++;
  2672. $result[$result['count']] = $row['id'];
  2673. $result['users_id'][] = $row['user_id'];
  2674. }
  2675. }
  2676. return $result;
  2677. }
  2678. function apply_auth_rule($db, $auth_record, $user_id)
  2679. {
  2680. if (empty($auth_record)) {
  2681. return null;
  2682. }
  2683. if (empty($user_id)) {
  2684. return $auth_record;
  2685. }
  2686. $user_rec = get_record($db, 'user_list', "id = ?", [(int)$user_id]);
  2687. if (empty($user_rec)) {
  2688. return $auth_record;
  2689. }
  2690. // Set filter and status by user
  2691. $auth_record['ou_id'] = $user_rec['ou_id'];
  2692. $auth_record['user_id'] = $user_rec['id'];
  2693. $auth_record['filter_group_id'] = $user_rec['filter_group_id'];
  2694. $auth_record['queue_id'] = $user_rec['queue_id'];
  2695. $auth_record['enabled'] = $user_rec['enabled'];
  2696. $auth_record['changed'] = 1;
  2697. // Maybe fill description?
  2698. if (!empty($user_rec['description']) && empty($auth_record['description'])) {
  2699. $auth_record['description'] = $user_rec['description'];
  2700. }
  2701. return $auth_record;
  2702. }
  2703. function fix_auth_rules($db)
  2704. {
  2705. // Cleanup hotspot subnet rules
  2706. $t_hotspot = get_records_sql($db, "SELECT id FROM ou WHERE default_users = 1 OR default_hotspot = 1");
  2707. if (!empty($t_hotspot)) {
  2708. foreach ($t_hotspot as $row) {
  2709. delete_record($db, "auth_rules", "ou_id = ?", [(int)$row['id']]);
  2710. }
  2711. }
  2712. $t_hotspot_subnets = get_records_sql($db, "SELECT subnet FROM subnets WHERE hotspot = 1");
  2713. if (!empty($t_hotspot_subnets)) {
  2714. foreach ($t_hotspot_subnets as $row) {
  2715. delete_record($db, "auth_rules", "rule = ?", [$row['subnet']]);
  2716. }
  2717. }
  2718. }
  2719. #---------------------------------------------------------------------------------------------------------------
  2720. function new_user($db, $user_info)
  2721. {
  2722. if (empty($user_info)) {
  2723. return null;
  2724. }
  2725. // Формируем логин и ФИО
  2726. if (!empty($user_info['mac'])) {
  2727. $user['login'] = mac_dotted($user_info['mac']);
  2728. } else {
  2729. $user['login'] = $user_info['ip'] ?? '';
  2730. }
  2731. if (!empty($user_info['dhcp_hostname'])) {
  2732. $user['description'] = ($user_info['ip'] ?? '') . '[' . $user_info['dhcp_hostname'] . ']';
  2733. } else {
  2734. $user['description'] = $user_info['ip'] ?? '';
  2735. }
  2736. // Проверяем существование логина и формируем уникальный
  2737. $base_login = $user['login'];
  2738. $login_count = get_count_records($db, "user_list",
  2739. "(login LIKE ?) OR (login = ?)",
  2740. [$base_login . '(%)', $base_login]
  2741. );
  2742. if (!empty($login_count) && $login_count > 0) {
  2743. $user['login'] = $base_login . "(" . ($login_count + 1) . ")";
  2744. }
  2745. // Назначаем OU и наследуем настройки
  2746. $user['ou_id'] = (int)($user_info['ou_id'] ?? 0);
  2747. if ($user['ou_id'] > 0) {
  2748. $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id = ?", [$user['ou_id']]);
  2749. if (!empty($ou_info)) {
  2750. $user['enabled'] = isset($ou_info['enabled']) ? (int)$ou_info['enabled'] : 0;
  2751. $user['queue_id'] = isset($ou_info['queue_id']) ? (int)$ou_info['queue_id'] : 0;
  2752. $user['filter_group_id'] = isset($ou_info['filter_group_id']) ? (int)$ou_info['filter_group_id'] : 0;
  2753. } else {
  2754. // Значения по умолчанию, если OU не найден
  2755. $user['enabled'] = 0;
  2756. $user['queue_id'] = 0;
  2757. $user['filter_group_id'] = 0;
  2758. }
  2759. } else {
  2760. // Значения по умолчанию при отсутствии OU
  2761. $user['enabled'] = 0;
  2762. $user['queue_id'] = 0;
  2763. $user['filter_group_id'] = 0;
  2764. }
  2765. // Создаём пользователя
  2766. $result = insert_record($db, "user_list", $user);
  2767. // Создаём автоматическое правило по MAC (если включено)
  2768. if (!empty($result)) {
  2769. $auto_mac_rule = (int)get_option($db, 64);
  2770. if ($auto_mac_rule && !empty($user_info['mac'])) {
  2771. $auth_rule = [
  2772. 'user_id' => $result,
  2773. 'rule_type' => 2,
  2774. 'rule' => mac_dotted($user_info['mac'])
  2775. ];
  2776. insert_record($db, "auth_rules", $auth_rule);
  2777. }
  2778. }
  2779. return $result;
  2780. }
  2781. function new_auth($db, $ip, $mac, $user_id)
  2782. {
  2783. if (empty($ip)) {
  2784. return null;
  2785. }
  2786. $ip_aton = ip2long($ip);
  2787. if ($ip_aton === false) {
  2788. return null;
  2789. }
  2790. $msg = '';
  2791. $user_id = (int)$user_id;
  2792. // Проверяем существование пары IP-MAC
  2793. if (!empty($mac)) {
  2794. $dotted_mac = mac_dotted($mac);
  2795. $auth_record = get_record_sql($db,
  2796. "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ? AND deleted = 0",
  2797. [$ip_aton, $dotted_mac]
  2798. );
  2799. if (!empty($auth_record)) {
  2800. LOG_WARNING($db, "Pair ip-mac already exists! Skip creating $ip [$mac] auth_id: " . $auth_record["id"]);
  2801. return $auth_record['id'];
  2802. }
  2803. }
  2804. // Настройки сохранения трафика
  2805. $save_traf = (int)get_option($db, 23);
  2806. $resurrection_id = null;
  2807. // Ищем удалённую запись с теми же IP и MAC
  2808. if (!empty($mac)) {
  2809. $old_auth_id = get_id_record($db, 'user_auth',
  2810. "deleted = 1 AND ip_int = ? AND mac = ?",
  2811. [$ip_aton, $mac]
  2812. );
  2813. } else {
  2814. $old_auth_id = get_id_record($db, 'user_auth',
  2815. "deleted = 1 AND ip_int = ? AND mac IS NULL",
  2816. [$ip_aton]
  2817. );
  2818. }
  2819. if (!empty($old_auth_id)) {
  2820. $resurrection_id = $old_auth_id;
  2821. $msg .= "Recovered auth_id: $resurrection_id with ip: $ip and mac: $mac ";
  2822. $auth = [
  2823. 'user_id' => $user_id,
  2824. 'deleted' => 0,
  2825. 'save_traf' => $save_traf
  2826. ];
  2827. update_record($db, "user_auth", "id = ?", $auth, [$resurrection_id]);
  2828. } else {
  2829. // Создаём новую запись
  2830. $msg .= "Create new ip record \r\nip: $ip\r\nmac: $mac\r\n";
  2831. $auth = [
  2832. 'deleted' => 0,
  2833. 'user_id' => $user_id,
  2834. 'ip' => $ip,
  2835. 'ip_int' => $ip_aton,
  2836. 'save_traf' => $save_traf
  2837. ];
  2838. if (!empty($mac)) {
  2839. $auth['mac'] = $mac;
  2840. }
  2841. $resurrection_id = insert_record($db, "user_auth", $auth);
  2842. }
  2843. // Применяем правила и обновляем запись
  2844. if (!empty($resurrection_id)) {
  2845. $auth_final = apply_auth_rule($db, $auth, $user_id);
  2846. update_record($db, "user_auth", "id = ?", $auth_final, [$resurrection_id]);
  2847. if (!is_hotspot($db, $ip) && !empty($msg)) {
  2848. LOG_WARNING($db, $msg);
  2849. }
  2850. if (is_hotspot($db, $ip) && !empty($msg)) {
  2851. LOG_INFO($db, $msg);
  2852. }
  2853. }
  2854. return $resurrection_id;
  2855. }
  2856. function resurrection_auth($db, $ip_record)
  2857. {
  2858. if (empty($ip_record) || empty($ip_record['ip'])) {
  2859. return null;
  2860. }
  2861. $ip = $ip_record['ip'];
  2862. $mac = $ip_record['mac'] ?? '';
  2863. $action = $ip_record['type'] ?? '';
  2864. $dhcp_hostname = $ip_record['hostname'] ?? '';
  2865. $hotspot_found = !empty($ip_record['hotspot']);
  2866. $description = $ip_record['description'] ?? '';
  2867. $ip_aton = ip2long($ip);
  2868. if ($ip_aton === false) {
  2869. return null;
  2870. }
  2871. // Проверяем существующую активную запись с теми же IP и MAC
  2872. $auth_record = get_record_sql($db,
  2873. "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ? AND deleted = 0",
  2874. [$ip_aton, $mac]
  2875. );
  2876. if (!empty($auth_record)) {
  2877. $user_info = get_record_sql($db,
  2878. "SELECT * FROM user_list WHERE id = ?",
  2879. [(int)$auth_record['user_id']]
  2880. );
  2881. LOG_DEBUG($db, "external dhcp user " . ($user_info['login'] ?? '') . " [" . $ip . "] auth_id: " . $auth_record['id']);
  2882. $auth_update = [];
  2883. if (isset($dhcp_hostname) && !empty($dhcp_hostname)) {
  2884. $auth_update['dhcp_hostname'] = $dhcp_hostname;
  2885. }
  2886. $auth_update['dhcp_action'] = $action;
  2887. $auth_update['dhcp_time'] = GetNowTimeString();
  2888. if ($action === 'add') {
  2889. $auth_update['last_found'] = GetNowTimeString();
  2890. }
  2891. update_record($db, "user_auth", "id = ?", $auth_update, [$auth_record['id']]);
  2892. return $auth_record['id'];
  2893. }
  2894. // Проверяем статическую подсеть
  2895. $ip_subnet = get_ip_subnet($db, $ip);
  2896. if (!empty($ip_subnet) && !empty($ip_subnet['static'])) {
  2897. LOG_WARNING($db, "Unknown pair ip+mac in static subnet! ip: $ip mac: [" . mac_dotted($mac) . "]. Skip");
  2898. return null;
  2899. }
  2900. $msg = '';
  2901. // Ищем запись с тем же IP (возможно, другой MAC)
  2902. $auth_record = get_record_sql($db,
  2903. "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0",
  2904. [$ip_aton]
  2905. );
  2906. if (!empty($auth_record)) {
  2907. if (empty($auth_record['mac'])) {
  2908. // Обновляем пустой MAC
  2909. $auth_update = [
  2910. 'mac' => mac_dotted($mac),
  2911. 'dhcp_action' => $action,
  2912. 'dhcp_time' => GetNowTimeString()
  2913. ];
  2914. if (!empty($dhcp_hostname)) {
  2915. $auth_update['dhcp_hostname'] = $dhcp_hostname;
  2916. }
  2917. if ($action === 'add') {
  2918. $auth_update['last_found'] = GetNowTimeString();
  2919. }
  2920. LOG_INFO($db, "for ip: $ip mac not found! Use empty record...");
  2921. update_record($db, "user_auth", "id = ?", $auth_update, [$auth_record['id']]);
  2922. return $auth_record['id'];
  2923. } else {
  2924. // MAC изменился - помечаем старую запись как удалённую
  2925. if (!$hotspot_found) {
  2926. 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']);
  2927. }
  2928. update_record($db, "user_auth", "id = ?", ['changed' => 1, 'deleted' => 1], [$auth_record['id']]);
  2929. }
  2930. }
  2931. // Создаём/находим пользователя
  2932. $new_user_info = get_new_user_id($db, $ip, $mac, $dhcp_hostname);
  2933. $new_user_id = null;
  2934. if (!empty($new_user_info['user_id'])) {
  2935. $new_user_id = $new_user_info['user_id'];
  2936. }
  2937. if (empty($new_user_id)) {
  2938. $new_user_id = new_user($db, $new_user_info);
  2939. }
  2940. if (empty($new_user_id)) {
  2941. return null;
  2942. }
  2943. $new_user_id = (int)$new_user_id;
  2944. $save_traf = (int)get_option($db, 23);
  2945. $resurrection_id = null;
  2946. // Ищем удалённую запись с теми же IP и MAC для восстановления
  2947. $auth_record = get_record_sql($db,
  2948. "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ?",
  2949. [$ip_aton, $mac]
  2950. );
  2951. if (!empty($auth_record)) {
  2952. // Восстанавливаем существующую запись
  2953. $resurrection_id = $auth_record['id'];
  2954. $msg .= "Recovered auth_id: $resurrection_id with ip: $ip and mac: $mac ";
  2955. $auth = [
  2956. 'dhcp_action' => $action,
  2957. 'user_id' => $new_user_id,
  2958. 'deleted' => 0,
  2959. 'dhcp_time' => GetNowTimeString(),
  2960. 'save_traf' => $save_traf
  2961. ];
  2962. if (!empty($description)) {
  2963. $auth['description'] = $description;
  2964. }
  2965. if (!empty($dhcp_hostname)) {
  2966. $auth['dhcp_hostname'] = $dhcp_hostname;
  2967. }
  2968. if ($action === 'add') {
  2969. $auth['last_found'] = GetNowTimeString();
  2970. }
  2971. update_record($db, "user_auth", "id = ?", $auth, [$resurrection_id]);
  2972. } else {
  2973. // Создаём новую запись
  2974. $msg .= "Создаём новый ip-адрес \r\nip: $ip\r\nmac: $mac\r\n";
  2975. $auth = [
  2976. 'deleted' => 0,
  2977. 'user_id' => $new_user_id,
  2978. 'ip' => $ip,
  2979. 'ip_int' => $ip_aton,
  2980. 'mac' => $mac,
  2981. 'dhcp_action' => $action,
  2982. 'dhcp_time' => GetNowTimeString(),
  2983. 'save_traf' => $save_traf
  2984. ];
  2985. if (!empty($description)) {
  2986. $auth['description'] = $description;
  2987. }
  2988. if (!empty($dhcp_hostname)) {
  2989. $auth['dhcp_hostname'] = $dhcp_hostname;
  2990. }
  2991. if ($action === 'add') {
  2992. $auth['last_found'] = GetNowTimeString();
  2993. }
  2994. $resurrection_id = insert_record($db, "user_auth", $auth);
  2995. }
  2996. // Применяем правила авторизации
  2997. if (!empty($resurrection_id)) {
  2998. $auth_final = apply_auth_rule($db, $auth, $new_user_id);
  2999. update_record($db, "user_auth", "id = ?", $auth_final, [$resurrection_id]);
  3000. $msg .= "filter: " . ($auth_final['filter_group_id'] ?? '') .
  3001. "\r\n queue_id: " . ($auth_final['queue_id'] ?? '') .
  3002. "\r\n enabled: " . ($auth_final['enabled'] ?? '') .
  3003. "\r\nid: $resurrection_id";
  3004. if (!$hotspot_found && !empty($msg)) {
  3005. LOG_WARNING($db, $msg);
  3006. }
  3007. if ($hotspot_found && !empty($msg)) {
  3008. LOG_INFO($db, $msg);
  3009. }
  3010. }
  3011. return $resurrection_id;
  3012. }
  3013. function get_auth($db, $current_auth)
  3014. {
  3015. if (!isset($current_auth) || $current_auth == 0) {
  3016. return null;
  3017. }
  3018. $t_login = get_record_sql($db,
  3019. "SELECT U.login, A.ip
  3020. FROM user_list AS U, user_auth AS A
  3021. WHERE A.user_id = U.id AND A.id = ?",
  3022. [(int)$current_auth]
  3023. );
  3024. if (!empty($t_login) && isset($t_login['login'])) {
  3025. return $t_login['login'] . "[" . $t_login['ip'] . "]";
  3026. }
  3027. return '';
  3028. }
  3029. function get_auth_by_mac($db, $mac)
  3030. {
  3031. if (empty($mac)) {
  3032. return ['auth' => 'Unknown', 'mac' => ''];
  3033. }
  3034. $mac_dotted = mac_dotted($mac);
  3035. $t_login = get_record_sql($db,
  3036. "SELECT U.id, U.login, A.id as auth_id, A.ip
  3037. FROM user_list AS U, user_auth AS A
  3038. WHERE A.user_id = U.id AND A.mac = ? AND A.deleted = 0
  3039. ORDER BY A.last_found DESC",
  3040. [$mac_dotted]
  3041. );
  3042. if (!empty($t_login) && isset($t_login['id'])) {
  3043. $user_id = (int)$t_login['id'];
  3044. $auth_id = (int)$t_login['auth_id'];
  3045. $login = htmlspecialchars($t_login['login']);
  3046. $ip = htmlspecialchars($t_login['ip']);
  3047. $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>';
  3048. } else {
  3049. $result['auth'] = 'Unknown';
  3050. }
  3051. $result['mac'] = expand_mac($db, $mac_dotted);
  3052. return $result;
  3053. }
  3054. function get_auth_mac($db, $current_auth)
  3055. {
  3056. if (!isset($current_auth) || $current_auth == 0) {
  3057. return null;
  3058. }
  3059. $t_login = get_record_sql($db,
  3060. "SELECT U.login, A.mac
  3061. FROM user_list AS U, user_auth AS A
  3062. WHERE A.user_id = U.id AND A.id = ?",
  3063. [(int)$current_auth]
  3064. );
  3065. // Исправлена опечатка: было $t_loing, стало $t_login
  3066. if (!empty($t_login) && isset($t_login['login'])) {
  3067. return $t_login['login'] . " [" . $t_login['mac'] . "]";
  3068. }
  3069. return '';
  3070. }
  3071. function add_auth_rule($db, $rule, $type, $user_id)
  3072. {
  3073. $user_id = (int)$user_id;
  3074. $type = (int)$type;
  3075. // Проверяем существование правила
  3076. $auth_rules = get_record_sql($db,
  3077. "SELECT * FROM auth_rules WHERE rule = ? AND rule_type = ?",
  3078. [$rule, $type]
  3079. );
  3080. if (empty($auth_rules)) {
  3081. // Создаём новое правило
  3082. $new = [
  3083. 'user_id' => $user_id,
  3084. 'rule_type' => $type,
  3085. 'rule' => $rule
  3086. ];
  3087. $rule_id = insert_record($db, "auth_rules", $new);
  3088. LOG_INFO($db, "Create auto rule for user_id: " . $user_id . " rule: " . $rule . " rule_type: " . $type);
  3089. } else {
  3090. if ($auth_rules['user_id'] !== $user_id) {
  3091. 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']);
  3092. $rule_id = 0;
  3093. } else {
  3094. $rule_id = $auth_rules['id'];
  3095. }
  3096. }
  3097. return $rule_id;
  3098. }
  3099. function update_auth_rule($db, $new, $rule_id = 0)
  3100. {
  3101. if (empty($new) || !isset($new['rule_type']) || !isset($new['rule'])) {
  3102. return 0;
  3103. }
  3104. $rule_id = (int)$rule_id;
  3105. $type = (int)$new['rule_type'];
  3106. $rule = $new['rule'];
  3107. // Проверяем существование другого правила с теми же параметрами
  3108. $auth_rules = get_record_sql($db,
  3109. "SELECT * FROM auth_rules WHERE rule = ? AND rule_type = ? AND id != ?",
  3110. [$rule, $type, $rule_id]
  3111. );
  3112. if (empty($auth_rules)) {
  3113. // Обновляем правило
  3114. $updated_id = update_record($db, "auth_rules", "id = ?", $new, [$rule_id]);
  3115. return $updated_id !== false ? $rule_id : 0;
  3116. } else {
  3117. // Правило уже существует у другого пользователя
  3118. LOG_WARNING($db, "Update auto rule id: " . $rule_id . " rule: " . $rule . " rule_type: " . $type . " failed! Already exists at user_id: " . $auth_rules['user_id']);
  3119. return 0;
  3120. }
  3121. }
  3122. function LOG_INFO($db, $msg, $auth_id = 0)
  3123. {
  3124. if (get_const('log_level') < L_INFO) {
  3125. return;
  3126. }
  3127. write_log($db, $msg, L_INFO, $auth_id);
  3128. }
  3129. function LOG_ERROR($db, $msg, $auth_id = 0)
  3130. {
  3131. if (get_const('log_level') < L_ERROR) {
  3132. return;
  3133. }
  3134. email(L_ERROR,$msg);
  3135. write_log($db, $msg, L_ERROR, $auth_id);
  3136. }
  3137. function LOG_VERBOSE($db, $msg, $auth_id = 0)
  3138. {
  3139. if (get_const('log_level') < L_VERBOSE) {
  3140. return;
  3141. }
  3142. write_log($db, $msg, L_VERBOSE, $auth_id);
  3143. }
  3144. function LOG_WARNING($db, $msg, $auth_id = 0)
  3145. {
  3146. if (get_const('log_level') < L_WARNING) {
  3147. return;
  3148. }
  3149. write_log($db, $msg, L_WARNING, $auth_id);
  3150. }
  3151. function LOG_DEBUG($db, $msg, $auth_id = 0)
  3152. {
  3153. if (!empty(get_const('debug')) and get_const('debug')) {
  3154. write_log($db, $msg, L_DEBUG, $auth_id);
  3155. }
  3156. }
  3157. function truncateByWords($string, $length = 100)
  3158. {
  3159. if (strlen($string) <= $length) {
  3160. return $string;
  3161. }
  3162. $wrapped = wordwrap($string, $length);
  3163. $shortened = substr($wrapped, 0, strpos($wrapped, "\n"));
  3164. return $shortened;
  3165. }
  3166. function get_first_line($msg)
  3167. {
  3168. if (empty($msg)) {
  3169. return;
  3170. }
  3171. preg_match('/(.*)(\n|\<br\>)/', $msg, $matches);
  3172. if (!empty($matches[1])) {
  3173. return $matches[1];
  3174. }
  3175. return truncateByWords($msg, 80);
  3176. }
  3177. function email($level = L_WARNING, $msg = '') {
  3178. if (empty($msg)) { return; }
  3179. // Получаем текущий IP
  3180. $currentIp = null;
  3181. if (!empty($_SESSION['ip'])) {
  3182. $currentIp = filter_var($_SESSION['ip'], FILTER_VALIDATE_IP);
  3183. }
  3184. if (!$currentIp && function_exists('get_client_ip')) {
  3185. $currentIp = filter_var(get_client_ip(), FILTER_VALIDATE_IP);
  3186. }
  3187. $currentIp = $currentIp ?: '127.0.0.1';
  3188. // Получаем текущий логин
  3189. $currentLogin = null;
  3190. if (!empty($_SESSION['login'])) {
  3191. $currentLogin = $_SESSION['login'];
  3192. }
  3193. if (!$currentLogin) {
  3194. $currentLogin = getParam('login', null, null) ?: getParam('api_login', null, null);
  3195. }
  3196. $currentLogin = htmlspecialchars($currentLogin ?: 'http', ENT_QUOTES, 'UTF-8');
  3197. // Обработка сообщения
  3198. $subjectPrefix = ($level === L_WARNING) ? "WARN: " : "ERROR: ";
  3199. $subject = $subjectPrefix . htmlspecialchars(get_first_line($msg), ENT_QUOTES, 'UTF-8') . "...";
  3200. $messageType = ($level === L_WARNING) ? 'WARNING' : 'ERROR';
  3201. // Формирование HTML-сообщения с экранированием
  3202. $safeMsg = nl2br(htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'));
  3203. $htmlMessage = "<html>
  3204. <body>
  3205. <h1>$messageType!</h1>
  3206. <p>Manager: $currentLogin</p>
  3207. <p>From: $currentIp</p>
  3208. <div>$safeMsg</div>
  3209. </body>
  3210. </html>";
  3211. // Заголовки письма
  3212. $senderEmail = filter_var(get_const('sender_email'), FILTER_VALIDATE_EMAIL);
  3213. if (!$senderEmail) {
  3214. error_log("Invalid sender email address");
  3215. return;
  3216. }
  3217. $boundary = md5(uniqid(time(), true));
  3218. $headers = [
  3219. 'From' => $senderEmail,
  3220. 'Reply-To' => $senderEmail,
  3221. 'X-Mailer' => 'PHP',
  3222. 'MIME-Version' => '1.0',
  3223. 'Content-Type' => 'multipart/mixed; boundary=' . $boundary,
  3224. 'Content-Transfer-Encoding' => 'base64'
  3225. ];
  3226. // Формирование тела письма
  3227. $message = "--$boundary\r\n" .
  3228. "Content-Type: text/html; charset=UTF-8\r\n" .
  3229. "Content-Transfer-Encoding: base64\r\n\r\n" .
  3230. chunk_split(base64_encode($htmlMessage)) . "\r\n" .
  3231. "--$boundary--";
  3232. // Отправка письма
  3233. $adminEmail = filter_var(get_const('admin_email'), FILTER_VALIDATE_EMAIL);
  3234. $additional_parameters = "-f ".$senderEmail;
  3235. if ($adminEmail) {
  3236. if (!mail($adminEmail, $subject, $message, $headers, $additional_parameters)) {
  3237. error_log("Failed to send email to $adminEmail");
  3238. }
  3239. } else {
  3240. error_log("Invalid admin email address");
  3241. }
  3242. }
  3243. function write_log($db, $msg, $level = L_INFO, $auth_id = 0)
  3244. {
  3245. if (!isset($msg)) { return; }
  3246. // Получаем текущий IP
  3247. $currentIp = null;
  3248. if (!empty($_SESSION['ip'])) {
  3249. $currentIp = filter_var($_SESSION['ip'], FILTER_VALIDATE_IP);
  3250. }
  3251. if (!$currentIp && function_exists('get_client_ip')) {
  3252. $currentIp = filter_var(get_client_ip(), FILTER_VALIDATE_IP);
  3253. }
  3254. $currentIp = $currentIp ?: '127.0.0.1';
  3255. // Получаем текущий логин
  3256. $currentLogin = null;
  3257. if (!empty($_SESSION['login'])) {
  3258. $currentLogin = $_SESSION['login'];
  3259. }
  3260. if (!$currentLogin) {
  3261. $currentLogin = getParam('login', null, null) ?: getParam('api_login', null, null);
  3262. }
  3263. $currentLogin = htmlspecialchars($currentLogin ?: 'http', ENT_QUOTES, 'UTF-8');
  3264. // Для уровня L_DEBUG пишем в error_log
  3265. if ($level === L_DEBUG) {
  3266. error_log("DEBUG: " . $msg);
  3267. return;
  3268. }
  3269. try {
  3270. // Используем подготовленный запрос PDO напрямую
  3271. $stmt = $db->prepare("INSERT INTO worklog(customer, message, level, auth_id, ip)
  3272. VALUES (:customer, :message, :level, :auth_id, :ip)");
  3273. $result = $stmt->execute([
  3274. ':customer' => $currentLogin,
  3275. ':message' => $msg,
  3276. ':level' => $level,
  3277. ':auth_id' => $auth_id,
  3278. ':ip' => $currentIp
  3279. ]);
  3280. return $result;
  3281. } catch (PDOException $e) {
  3282. // В случае ошибки логируем в error_log, чтобы избежать рекурсии
  3283. error_log("Error writing log to database: " . $e->getMessage());
  3284. return false;
  3285. }
  3286. }
  3287. function print_year_select($year_name, $year)
  3288. {
  3289. print "<select id=\"$year_name\" name=\"$year_name\" >\n";
  3290. for ($i = $year - 10; $i <= $year + 10; $i++) {
  3291. print_select_item($i, $i, $year);
  3292. }
  3293. print "</select>\n";
  3294. }
  3295. function print_date_select($dd, $mm, $yy)
  3296. {
  3297. if ($dd >= 1) {
  3298. print "<b>День</b>\n";
  3299. print "<select id=\"day\" name=\"day\" >\n";
  3300. for ($i = 1; $i <= 31; $i++) {
  3301. print_select_item($i, $i, $dd);
  3302. }
  3303. print "</select>\n";
  3304. }
  3305. if ($mm >= 1) {
  3306. print "<b>Месяц</b>\n";
  3307. print "<select id=\"month\" name=\"month\" >\n";
  3308. for ($i = 1; $i <= 12; $i++) {
  3309. $tmp_date = DateTimeImmutable::createFromFormat('U', strtotime("$i/01/$yy"));
  3310. $month_name = $tmp_date->format('F');
  3311. print_select_item($month_name, $i, $mm);
  3312. }
  3313. print "</select>\n";
  3314. }
  3315. print "<b>Год</b>\n";
  3316. print_year_select('year', $yy);
  3317. }
  3318. function print_date_select2($dd, $mm, $yy)
  3319. {
  3320. if ($dd >= 1) {
  3321. print "<b>День</b>\n";
  3322. print "<select id=\"day2\" name=\"day2\" >\n";
  3323. for ($i = 1; $i <= 31; $i++) {
  3324. print_select_item($i, $i, $dd);
  3325. }
  3326. print "</select>\n";
  3327. }
  3328. if ($mm >= 1) {
  3329. print "<b>Месяц</b>\n";
  3330. print "<select id=\"month2\" name=\"month2\" >\n";
  3331. for ($i = 1; $i <= 12; $i++) {
  3332. $tmp_date = DateTimeImmutable::createFromFormat('U', strtotime("$i/01/$yy"));
  3333. $month_name = $tmp_date->format('F');
  3334. print_select_item($month_name, $i, $mm);
  3335. }
  3336. print "</select>\n";
  3337. }
  3338. print "<b>Год</b>\n";
  3339. print_year_select('year2', $yy);
  3340. }
  3341. function is_up($ip)
  3342. {
  3343. if (!isset($ip) or strlen($ip) == 0) {
  3344. return false;
  3345. }
  3346. exec(sprintf('ping -i .3 -c 1 -W 5 %s', escapeshellarg($ip)), $res, $rval);
  3347. return $rval == 0;
  3348. }
  3349. function apply_device_lock($db, $device_id, $iteration = 0)
  3350. {
  3351. $iteration++;
  3352. if ($iteration > 2) {
  3353. return false;
  3354. }
  3355. // Извлекаем исходную временную метку (без UNIX_TIMESTAMP)
  3356. $dev = get_record_sql($db,
  3357. 'SELECT discovery_locked, locked_timestamp FROM devices WHERE id = ? AND discovery_locked > 0',
  3358. [(int)$device_id]
  3359. );
  3360. // Проверяем, есть ли запись и валидна ли временная метка
  3361. if (empty($dev) || is_empty_datetime($dev['locked_timestamp'])) {
  3362. LOG_DEBUG($db, "Snmp discovery lock not found. Set and discovery.");
  3363. return set_lock_discovery($db, (int)$device_id);
  3364. }
  3365. // Преобразуем строку даты в Unix timestamp
  3366. try {
  3367. // Удаляем микросекунды (если есть, как в PostgreSQL)
  3368. $ts_str = preg_replace('/\.\d+$/', '', $dev['locked_timestamp']);
  3369. $dt = new DateTime($ts_str);
  3370. $u_locked_timestamp = $dt->getTimestamp();
  3371. } catch (Exception $e) {
  3372. // Если парсинг не удался — считаем блокировку недействительной
  3373. LOG_DEBUG($db, "Invalid lock timestamp format. Resetting lock.");
  3374. return set_lock_discovery($db, (int)$device_id);
  3375. }
  3376. $now = time();
  3377. $wait_time = ($u_locked_timestamp + SNMP_LOCK_TIMEOUT) - $now;
  3378. LOG_DEBUG($db, "Check snmp lock for device id: " . $device_id . ". Lock timestamp: " . $u_locked_timestamp . ", now: " . $now);
  3379. if ($wait_time <= 0) {
  3380. LOG_DEBUG($db, "The lock is already expired. Set new lock.");
  3381. return set_lock_discovery($db, (int)$device_id);
  3382. }
  3383. LOG_VERBOSE($db, "Snmp discovery lock for device id: $device_id found! Need wait " . $wait_time . " sec.");
  3384. sleep($wait_time);
  3385. LOG_VERBOSE($db, "Try set new lock and continue discovery for device id: " . $device_id);
  3386. return apply_device_lock($db, (int)$device_id, $iteration);
  3387. }
  3388. function set_lock_discovery($db, $device_id)
  3389. {
  3390. $new['discovery_locked'] = 1;
  3391. $new['locked_timestamp'] = GetNowTimeString();
  3392. if (update_record($db, 'devices', 'id = ?', $new, [(int)$device_id])) {
  3393. return true;
  3394. }
  3395. return false;
  3396. }
  3397. function unset_lock_discovery($db, $device_id)
  3398. {
  3399. $new['discovery_locked'] = 0;
  3400. $new['locked_timestamp'] = GetNowTimeString();
  3401. if (update_record($db, 'devices', 'id = ?', $new, [(int)$device_id])) {
  3402. return true;
  3403. }
  3404. return false;
  3405. }
  3406. function set_port_for_group($db, $group_id, $place_id, $state)
  3407. {
  3408. $group_id = (int)$group_id;
  3409. $place_id = (int)$place_id;
  3410. $state = (int)$state;
  3411. // Получаем список авторизаций для группы
  3412. $auth_list = get_records_sql($db,
  3413. 'SELECT user_auth.id, user_auth.dns_name, user_auth.ip
  3414. FROM user_auth, user_list
  3415. WHERE user_auth.user_id = user_list.id
  3416. AND user_auth.deleted = 0
  3417. AND user_list.ou_id = ?',
  3418. [$group_id]
  3419. );
  3420. LOG_VERBOSE($db, 'Mass port state change started!');
  3421. // Обработка списка авторизаций
  3422. foreach ($auth_list as $row) {
  3423. $auth_id = (int)$row['id'];
  3424. // Формируем фильтр по месту
  3425. if ($place_id == 0) {
  3426. $place_condition = '1=1';
  3427. $place_params = [];
  3428. } else {
  3429. $place_condition = 'D.building_id = ?';
  3430. $place_params = [$place_id];
  3431. }
  3432. // Получение информации об устройстве
  3433. $devSQL = 'SELECT D.id, D.device_name, D.vendor_id, D.device_model, D.ip,
  3434. DP.port, DP.snmp_index
  3435. FROM devices AS D, device_ports AS DP, connections AS C
  3436. WHERE ' . $place_condition . '
  3437. AND D.id = DP.device_id
  3438. AND DP.id = C.port_id
  3439. AND C.auth_id = ?';
  3440. $params = array_merge($place_params, [$auth_id]);
  3441. $dev_info = get_record_sql($db, $devSQL, $params);
  3442. if (empty($dev_info)) {
  3443. continue;
  3444. }
  3445. // Получение устройства
  3446. $device = get_record($db, 'devices', "id = ?", [(int)$dev_info['id']]);
  3447. $snmp = getSnmpAccess($device);
  3448. // Определение режима и обновление nagios_handler
  3449. if ($state == 1) {
  3450. $mode = 'enable';
  3451. update_record($db, 'user_auth',
  3452. 'id = ? AND nagios_handler = ?',
  3453. ['nagios_handler' => 'restart-port'],
  3454. [$auth_id, 'manual-mode']
  3455. );
  3456. } else {
  3457. $mode = 'disable';
  3458. update_record($db, 'user_auth',
  3459. 'id = ? AND nagios_handler = ?',
  3460. ['nagios_handler' => 'manual-mode'],
  3461. [$auth_id, 'restart-port']
  3462. );
  3463. }
  3464. // Логирование
  3465. LOG_INFO($db, "At device " . htmlspecialchars($dev_info['device_name']) .
  3466. " [" . htmlspecialchars($dev_info['ip']) . "] " .
  3467. $mode . " port " . htmlspecialchars($dev_info['port']) .
  3468. " for auth_id: " . $auth_id .
  3469. " (" . htmlspecialchars($row['ip']) . " [" . htmlspecialchars($row['dns_name']) . "])");
  3470. // Установка состояния порта
  3471. set_port_state($dev_info['vendor_id'], $dev_info['snmp_index'],
  3472. $dev_info['ip'], $snmp, $state);
  3473. // Установка состояния PoE
  3474. set_port_poe_state($dev_info['vendor_id'], $dev_info['port'],
  3475. $dev_info['snmp_index'], $dev_info['ip'],
  3476. $snmp, $state);
  3477. }
  3478. LOG_VERBOSE($db, 'Mass port state change stopped.');
  3479. }
  3480. function get_mac_vendor($db, $mac)
  3481. {
  3482. if (empty($mac)) {
  3483. return '';
  3484. }
  3485. $mac = mac_dotted($mac);
  3486. $mac_prefixes = [
  3487. $mac, // полный MAC
  3488. substr($mac, 0, 14), // OUI + 2 байта
  3489. substr($mac, 0, 11), // OUI + 1 байт
  3490. substr($mac, 0, 8) // только OUI
  3491. ];
  3492. $vendor = null;
  3493. foreach ($mac_prefixes as $oui) {
  3494. if (empty($oui)) continue;
  3495. $vendor = get_record_sql($db, 'SELECT companyname,companyaddress FROM mac_vendors WHERE oui = ?', [$oui]);
  3496. if (!empty($vendor)) { break; }
  3497. }
  3498. if (empty($vendor)) { return ''; }
  3499. $address = $vendor['companyaddress'] ?? null;
  3500. $name = $vendor['companyname'] ?? null;
  3501. if (!empty($address)) {
  3502. return $address;
  3503. }
  3504. return $name ?? '';
  3505. }
  3506. function strHexToBin($number)
  3507. {
  3508. $result = '';
  3509. for ($i = 0; $i < strlen($number); $i++) {
  3510. $conv = base_convert($number[$i], 16, 2);
  3511. $result .= str_pad($conv, 4, '0', STR_PAD_LEFT);
  3512. }
  3513. return $result;
  3514. }
  3515. function dec_to_hex($mac)
  3516. {
  3517. if (!isset($mac)) {
  3518. return;
  3519. }
  3520. $mac_array = explode('.', $mac);
  3521. for ($i = 0; $i < count($mac_array); $i++) {
  3522. $hex_i = dechex($mac_array[$i]);
  3523. if (strlen($hex_i) == 1) {
  3524. $hex_i = "0" . $hex_i;
  3525. }
  3526. $mac_array[$i] = $hex_i;
  3527. }
  3528. $hex_mac = implode(':', $mac_array);
  3529. return $hex_mac;
  3530. }
  3531. function mac_simplify($mac)
  3532. {
  3533. if (!isset($mac)) {
  3534. return;
  3535. }
  3536. $mac = strtolower(trim($mac));
  3537. $mac = preg_replace('/(\.|:|-)/', '', $mac);
  3538. return $mac;
  3539. }
  3540. function mac_dotted($mac)
  3541. {
  3542. if (!isset($mac)) {
  3543. return;
  3544. }
  3545. $mac = mac_simplify($mac);
  3546. $mac = preg_replace('/(\S{2})(\S{2})?(\S{2})?(\S{2})?(\S{2})?(\S{2})?/', '$1:$2:$3:$4:$5:$6', $mac);
  3547. $mac = preg_replace('/\:+$/', '', $mac, 5);
  3548. return $mac;
  3549. }
  3550. function unbind_ports($db, $device_id)
  3551. {
  3552. $device_id = (int)$device_id;
  3553. $target = get_records_sql($db,
  3554. "SELECT target_port_id, id FROM device_ports WHERE device_id = ?",
  3555. [$device_id]
  3556. );
  3557. foreach ($target as $row) {
  3558. $port_id = (int)$row['id'];
  3559. $target_port_id = (int)$row['target_port_id'];
  3560. // Обнуляем ссылки на этот порт у других портов
  3561. update_record($db, "device_ports", "target_port_id = ?", ['target_port_id' => 0], [$port_id]);
  3562. // Обнуляем ссылку этого порта на другой порт
  3563. update_record($db, "device_ports", "id = ?", ['target_port_id' => 0], [$port_id]);
  3564. }
  3565. }
  3566. function bind_ports($db, $port_id, $target_id)
  3567. {
  3568. $port_id = (int)$port_id;
  3569. $target_id = (int)$target_id;
  3570. // Отвязываем текущее соединение
  3571. $new = ['target_port_id' => 0];
  3572. $old_target = get_record_sql($db,
  3573. "SELECT target_port_id FROM device_ports WHERE id = ?",
  3574. [$port_id]
  3575. );
  3576. if (!empty($old_target) && !empty($old_target['target_port_id'])) {
  3577. $old_target_id = (int)$old_target['target_port_id'];
  3578. update_record($db, "device_ports", "id = ?", $new, [$old_target_id]);
  3579. }
  3580. // Обнуляем текущий порт
  3581. update_record($db, "device_ports", "id = ?", $new, [$port_id]);
  3582. // Создаём новое соединение
  3583. if ($target_id > 0) {
  3584. // Связываем port_id -> target_id
  3585. update_record($db, "device_ports", "id = ?", ['target_port_id' => $target_id], [$port_id]);
  3586. // Связываем target_id -> port_id
  3587. update_record($db, "device_ports", "id = ?", ['target_port_id' => $port_id], [$target_id]);
  3588. }
  3589. }
  3590. function expand_device_name($db, $name)
  3591. {
  3592. if (empty($name)) {
  3593. return '';
  3594. }
  3595. $device_id = get_device_id($db, $name);
  3596. if (isset($device_id) && $device_id > 0) {
  3597. $safe_name = htmlspecialchars($name);
  3598. $safe_id = (int)$device_id;
  3599. return '<a href="/admin/devices/editdevice.php?id=' . $safe_id . '">' . $safe_name . '</a>';
  3600. }
  3601. return $name;
  3602. }
  3603. function expand_mac($db, $mac)
  3604. {
  3605. if (empty($mac)) {
  3606. return '';
  3607. }
  3608. $mac = mac_dotted($mac);
  3609. $safe_vendor = get_mac_vendor($db, $mac);
  3610. $safe_mac = $mac;
  3611. $safe_url_mac = urlencode($mac);
  3612. if (!empty($safe_vendor)) {
  3613. return '<a href="/admin/logs/mac.php?mac=' . $safe_url_mac . '"><p title="' . $safe_vendor . '">' . $safe_mac . '</p></a>';
  3614. } else {
  3615. return '<a href="/admin/logs/mac.php?mac=' . $safe_url_mac . '">' . $safe_mac . '</a>';
  3616. }
  3617. }
  3618. function expand_log_str($db, $msg)
  3619. {
  3620. if (empty($msg)) {
  3621. return '';
  3622. }
  3623. $result = $msg;
  3624. // === Замена auth_id ===
  3625. $auth_pattern = '/(auth_id:|auth|auth id:|auth id)\s+(\d+)/i';
  3626. $result = preg_replace_callback($auth_pattern, function($matches) {
  3627. $id = (int)$matches[2];
  3628. $safe_id = htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
  3629. return '<a href="/admin/users/editauth.php?id=' . $id . '">auth_id:' . $safe_id . '</a>';
  3630. }, $result);
  3631. // === Замена user_id ===
  3632. $user_pattern = '/(user_id:|user|user id:|user id)\s+(\d+)/i';
  3633. $result = preg_replace_callback($user_pattern, function($matches) {
  3634. $id = (int)$matches[2];
  3635. $safe_id = htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
  3636. return '<a href="/admin/users/edituser.php?id=' . $id . '">user_id:' . $safe_id . '</a>';
  3637. }, $result);
  3638. // === Замена MAC-адресов в формате [1234567890ab] ===
  3639. $mac_pattern1 = '/\s*\[(\w{12})\]\s*/i';
  3640. $result = preg_replace_callback($mac_pattern1, function($matches) {
  3641. $mac_raw = $matches[1];
  3642. $mac_dotted = mac_dotted($mac_raw);
  3643. $safe_mac = htmlspecialchars($mac_dotted, ENT_QUOTES, 'UTF-8');
  3644. $url_mac = urlencode($mac_dotted);
  3645. return ' <a href="/admin/logs/mac.php?mac=' . $url_mac . '">' . $safe_mac . '</a> ';
  3646. }, $result);
  3647. // === Замена MAC-адресов в формате "mac: xx:xx:xx:xx:xx:xx" ===
  3648. $mac_pattern2 = '/\s*mac:\s+([\w:]{17})/i';
  3649. $result = preg_replace_callback($mac_pattern2, function($matches) {
  3650. $mac_raw = $matches[1];
  3651. $mac_dotted = mac_dotted($mac_raw);
  3652. $safe_mac = htmlspecialchars($mac_dotted, ENT_QUOTES, 'UTF-8');
  3653. $url_mac = urlencode($mac_dotted);
  3654. return ' mac: <a href="/admin/logs/mac.php?mac=' . $url_mac . '">' . $safe_mac . '</a> ';
  3655. }, $result);
  3656. // === Замена device name ===
  3657. $device_pattern1 = '/at device\s+([\w.\-]+)/i';
  3658. $result = preg_replace_callback($device_pattern1, function($matches) use ($db) {
  3659. $device_name = $matches[1];
  3660. $device_id = get_device_id($db, $device_name);
  3661. if ($device_id && $device_id > 0) {
  3662. $safe_name = htmlspecialchars($device_name, ENT_QUOTES, 'UTF-8');
  3663. return 'at device <a href="/admin/devices/editdevice.php?id=' . (int)$device_id . '">' . $safe_name . '</a>';
  3664. }
  3665. return $matches[0];
  3666. }, $result);
  3667. // === Замена device_id ===
  3668. $device_pattern2 = '/(device_id:|device id:|device id|device_id)\s+(\d+)/i';
  3669. $result = preg_replace_callback($device_pattern2, function($matches) {
  3670. $id = (int)$matches[2];
  3671. $safe_id = htmlspecialchars($id, ENT_QUOTES, 'UTF-8');
  3672. return 'device_id: <a href="/admin/devices/editdevice.php?id=' . $id . '">' . $safe_id . '</a>';
  3673. }, $result);
  3674. // === Замена IP-адресов ===
  3675. $ip_pattern = '/\s*ip:\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*/i';
  3676. $result = preg_replace_callback($ip_pattern, function($matches) use ($db) {
  3677. $ip = $matches[1];
  3678. if (filter_var($ip, FILTER_VALIDATE_IP)) {
  3679. $auth_id = get_auth_by_ip($db, $ip);
  3680. if ($auth_id && $auth_id > 0) {
  3681. $safe_ip = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
  3682. return ' ip: <a href="/admin/users/editauth.php?id=' . (int)$auth_id . '">' . $safe_ip . '</a> ';
  3683. }
  3684. }
  3685. return $matches[0];
  3686. }, $result);
  3687. return $result;
  3688. }
  3689. function is_auth_bind_changed($db, $id, $ip, $mac)
  3690. {
  3691. $old_record = get_record_sql($db,
  3692. "SELECT ip, mac FROM user_auth WHERE id = ?",
  3693. [(int)$id]
  3694. );
  3695. if (empty($old_record) || empty($old_record["ip"]) || empty($old_record["mac"])) {
  3696. return 0;
  3697. }
  3698. if ($old_record["ip"] !== $ip || $old_record["mac"] !== $mac) {
  3699. LOG_VERBOSE($db, "Changed ip or mac for auth record!");
  3700. return 1;
  3701. }
  3702. return 0;
  3703. }
  3704. function copy_auth($db, $id, $new_auth)
  3705. {
  3706. $id = (int)$id;
  3707. $old_record = get_record_sql($db,
  3708. "SELECT * FROM user_auth WHERE id = ?",
  3709. [$id]
  3710. );
  3711. if (empty($old_record)) {
  3712. return null;
  3713. }
  3714. delete_record($db, "user_auth", "id = ?", [$id]);
  3715. $new_auth["user_id"] = $old_record["user_id"];
  3716. $new_auth["changed"] = 1;
  3717. $new_auth["changed_time"] = GetNowTimeString();
  3718. $new_id = insert_record($db, "user_auth", $new_auth);
  3719. if (!empty($new_id)) {
  3720. LOG_VERBOSE($db, "Old record with id: $id deleted. Created new auth record for new ip+mac id: $new_id!");
  3721. }
  3722. return $new_id;
  3723. }
  3724. function get_dns_name($db, $id)
  3725. {
  3726. $auth_record = get_record_sql($db,
  3727. "SELECT dns_name FROM user_auth WHERE id = ?",
  3728. [(int)$id]
  3729. );
  3730. if (!empty($auth_record) && !empty($auth_record['dns_name'])) {
  3731. return $auth_record['dns_name'];
  3732. }
  3733. return '';
  3734. }
  3735. function get_cacti_graph($host_ip, $port_index)
  3736. {
  3737. // Проверка конфигурации Cacti
  3738. if (empty(get_const('cacti_url'))) {
  3739. return null;
  3740. }
  3741. if (empty(CACTI_DB_HOST) || empty(CACTI_DB_USER) || empty(CACTI_DB_PASS) || empty(CACTI_DB_NAME)) {
  3742. return null;
  3743. }
  3744. // Установка соединения с БД Cacti
  3745. $cacti_db_link = new_connection('mysql', CACTI_DB_HOST, CACTI_DB_USER, CACTI_DB_PASS, CACTI_DB_NAME);
  3746. if (!$cacti_db_link) {
  3747. return false;
  3748. }
  3749. // Поиск хоста по IP-адресу
  3750. $cacti_host = get_record_sql($cacti_db_link,
  3751. "SELECT * FROM host WHERE hostname = ?",
  3752. [$host_ip]
  3753. );
  3754. if (empty($cacti_host) || empty($cacti_host["id"])) {
  3755. return null;
  3756. }
  3757. $host_id = (int)$cacti_host["id"];
  3758. $port_index = (string)$port_index; // SNMP index может быть строкой
  3759. // Получение ID шаблонов графиков для трафика интерфейсов
  3760. $traffic_templates = get_records_sql($cacti_db_link,
  3761. "SELECT id FROM graph_templates WHERE name LIKE 'Interface - Traffic%'"
  3762. );
  3763. if (empty($traffic_templates)) {
  3764. return null;
  3765. }
  3766. $template_ids = [];
  3767. foreach ($traffic_templates as $template) {
  3768. $template_ids[] = (int)$template['id'];
  3769. }
  3770. // Формирование условия IN для параметризованного запроса
  3771. $placeholders = str_repeat('?,', count($template_ids) - 1) . '?';
  3772. // Поиск графика по хосту, SNMP-индексу и шаблону
  3773. $cacti_graph = get_record_sql($cacti_db_link,
  3774. "SELECT * FROM graph_local
  3775. WHERE host_id = ?
  3776. AND snmp_index = ?
  3777. AND graph_template_id IN ($placeholders)
  3778. ORDER BY id ASC",
  3779. array_merge([$host_id, $port_index], $template_ids)
  3780. );
  3781. if (empty($cacti_graph) || empty($cacti_graph["id"])) {
  3782. return null;
  3783. }
  3784. $graph_id = (int)$cacti_graph["id"];
  3785. $result = rtrim(get_const('cacti_url'), '/') . "/graph_image.php?local_graph_id=" . $graph_id;
  3786. return $result;
  3787. }
  3788. function print_select_item($description, $value, $current)
  3789. {
  3790. if ((string)$value === (string)$current) {
  3791. print "<option value='" . $value . "' selected>$description</option>";
  3792. } else {
  3793. print "<option value='" . $value . "'>$description</option>";
  3794. }
  3795. }
  3796. function print_select_simple($description, $value)
  3797. {
  3798. print "<option value=$value>$description</option>";
  3799. }
  3800. function print_select_item_ext($description, $value, $current, $disabled)
  3801. {
  3802. if ((string)$value === (string)$current) {
  3803. print "<option value=$value selected>$description</option>";
  3804. } else {
  3805. if (!$disabled) {
  3806. print "<option value=$value>$description</option>";
  3807. } else {
  3808. print "<option disabled value=$value>$description</option>";
  3809. }
  3810. }
  3811. }
  3812. function print_row_at_pages($name, $value)
  3813. {
  3814. print "<select id='" . $name . "' name='" . $name . "'>\n";
  3815. print_select_item(WEB_select_item_more, pow(10, 10), $value);
  3816. print_select_item('25', 25, $value);
  3817. print_select_item('50', 50, $value);
  3818. print_select_item('100', 100, $value);
  3819. print_select_item('200', 200, $value);
  3820. print_select_item('500', 500, $value);
  3821. print_select_item('1000', 1000, $value);
  3822. print_select_item('2000', 2000, $value);
  3823. print "</select>\n";
  3824. }
  3825. function print_navigation($base_url, $page, $displayed, $count_records, $total)
  3826. {
  3827. if ($total <= 1) {
  3828. echo "<div align=left class=records>";
  3829. echo "| Total records: $count_records";
  3830. echo "</div>";
  3831. return;
  3832. }
  3833. // Копируем текущие GET-параметры
  3834. $params = $_GET;
  3835. // Убираем page, чтобы не дублировать
  3836. unset($params['page']);
  3837. // Формируем строку запроса без page
  3838. $query_string = http_build_query($params);
  3839. // Определяем разделитель
  3840. $separator = parse_url($base_url, PHP_URL_QUERY) ? '&' : '?';
  3841. if ($query_string) {
  3842. $url_with_params = $base_url . $separator . $query_string;
  3843. } else {
  3844. $url_with_params = $base_url;
  3845. }
  3846. // Вспомогательная функция для генерации ссылки
  3847. $make_link = function($p) use ($url_with_params, $separator) {
  3848. $page_param = 'page=' . (int)$p;
  3849. if (parse_url($url_with_params, PHP_URL_QUERY)) {
  3850. return $url_with_params . '&' . $page_param;
  3851. } else {
  3852. return $url_with_params . '?' . $page_param;
  3853. }
  3854. };
  3855. // Две назад
  3856. $pagetwoleft = ($page - 2 > 0)
  3857. ? "<a class='first_page_link' href='" . htmlspecialchars($make_link($page - 2)) . "'>" . ($page - 2) . "</a> "
  3858. : '';
  3859. // Одна назад
  3860. $pageoneleft = ($page - 1 > 0)
  3861. ? "<a class='first_page_link' href='" . htmlspecialchars($make_link($page - 1)) . "'>" . ($page - 1) . "</a> "
  3862. : '';
  3863. $pagetemp = ($page - 1 > 0) ? $page - 1 : null;
  3864. // Две вперёд
  3865. $pagetworight = ($page + 2 <= $total)
  3866. ? " <a class='first_page_link' href='" . htmlspecialchars($make_link($page + 2)) . "'>" . ($page + 2) . "</a>"
  3867. : '';
  3868. // Одна вперёд
  3869. $pageoneright = ($page + 1 <= $total)
  3870. ? " <a class='first_page_link' href='" . htmlspecialchars($make_link($page + 1)) . "'>" . ($page + 1) . "</a>"
  3871. : '';
  3872. $pagetemp2 = ($page + 1 <= $total) ? $page + 1 : null;
  3873. // В начало
  3874. $pagerevp = '';
  3875. if ($page != 1 && $pagetemp != 1 && $pagetemp != 2) {
  3876. $pagerevp = "<a href='" . htmlspecialchars($make_link(1)) . "' class='first_page_link' title='В начало'><<</a> ";
  3877. }
  3878. // В конец
  3879. $nextp = '';
  3880. if ($page != $total && $pagetemp2 != ($total - 1) && $pagetemp2 != $total) {
  3881. $nextp = " ... <a href='" . htmlspecialchars($make_link($total)) . "' class='first_page_link'>$total</a>";
  3882. }
  3883. echo "<div align=left class=records>";
  3884. echo $pagerevp . $pagetwoleft . $pageoneleft;
  3885. echo '<span class="num_page_not_link"><b>' . (int)$page . '</b></span>';
  3886. echo $pageoneright . $pagetworight . $nextp;
  3887. echo " | Total records: " . (int)$count_records;
  3888. echo "</div>";
  3889. }
  3890. function get_option($db, $option_id)
  3891. {
  3892. // Валидация входного параметра
  3893. if (!is_numeric($option_id) || $option_id <= 0) {
  3894. return null;
  3895. }
  3896. $sql = "
  3897. SELECT
  3898. COALESCE(c.value, co.default_value) AS value,
  3899. co.option_type
  3900. FROM config_options co
  3901. LEFT JOIN config c ON c.option_id = co.id
  3902. WHERE co.id = ?
  3903. ";
  3904. $record = get_record_sql($db, $sql, [(int)$option_id]);
  3905. if ($record && isset($record['value'])) {
  3906. return $record['value'];
  3907. }
  3908. return null;
  3909. }
  3910. function is_option($db, $option_id)
  3911. {
  3912. if (!is_numeric($option_id) || $option_id <= 0) {
  3913. return false;
  3914. }
  3915. $option = get_record($db, "config", "option_id = ?", [(int)$option_id]);
  3916. if (empty($option) || empty($option['value'])) {
  3917. return false;
  3918. }
  3919. return true;
  3920. }
  3921. function set_option($db, $option_id, $value)
  3922. {
  3923. if (!is_numeric($option_id) || $option_id <= 0) {
  3924. return false;
  3925. }
  3926. $option = ['value' => $value];
  3927. $result = update_record($db, 'config', "option_id = ?", $option, [(int)$option_id]);
  3928. return $result !== false;
  3929. }
  3930. function is_subnet_aton($subnet, $ip)
  3931. {
  3932. if (empty($subnet) || empty($ip)) {
  3933. return false;
  3934. }
  3935. // Проверяем корректность IP-адреса
  3936. if (!is_numeric($ip)) {
  3937. return false;
  3938. }
  3939. $range = cidrToRange($subnet);
  3940. if ($range === false) {
  3941. return false;
  3942. }
  3943. $ip_start = ip2long($range[0]);
  3944. $ip_end = ip2long($range[1]);
  3945. if ($ip_start === false || $ip_end === false) {
  3946. return false;
  3947. }
  3948. if ($ip >= $ip_start && $ip <= $ip_end) {
  3949. return true;
  3950. }
  3951. return false;
  3952. }
  3953. function get_new_user_id($db, $ip, $mac, $hostname)
  3954. {
  3955. $result = [
  3956. 'ip' => $ip,
  3957. 'mac' => !empty($mac) ? mac_dotted($mac) : '',
  3958. 'hostname' => $hostname,
  3959. 'user_id' => null,
  3960. 'ou_id' => null
  3961. ];
  3962. $ip_aton = ip2long($ip);
  3963. if ($ip_aton === false) {
  3964. // Некорректный IP - используем значения по умолчанию
  3965. if (empty($result['ou_id'])) {
  3966. $result['ou_id'] = get_const('default_user_ou_id');
  3967. }
  3968. return $result;
  3969. }
  3970. // Проверка hotspot
  3971. if (is_hotspot($db, $ip)) {
  3972. $result['ou_id'] = get_const('default_hotspot_ou_id');
  3973. return $result;
  3974. }
  3975. // === Правила для пользователей ===
  3976. // IP правила (rule_type = 1)
  3977. if (!empty($ip)) {
  3978. $t_rules = get_records_sql($db,
  3979. "SELECT * FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  3980. );
  3981. foreach ($t_rules as $row) {
  3982. if (!empty($row['rule']) && is_subnet_aton($row['rule'], $ip_aton)) {
  3983. $result['user_id'] = (int)$row['user_id'];
  3984. return $result;
  3985. }
  3986. }
  3987. }
  3988. // MAC правила (rule_type = 2)
  3989. if (!empty($mac)) {
  3990. $mac_simplified = mac_simplify($mac);
  3991. $mac_rules = get_records_sql($db,
  3992. "SELECT * FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  3993. );
  3994. foreach ($mac_rules as $row) {
  3995. if (!empty($row['rule'])) {
  3996. $pattern = '/' . preg_quote(mac_simplify($row['rule']), '/') . '/';
  3997. if (preg_match($pattern, $mac_simplified)) {
  3998. $result['user_id'] = (int)$row['user_id'];
  3999. return $result;
  4000. }
  4001. }
  4002. }
  4003. }
  4004. // Hostname правила (rule_type = 3)
  4005. if (!empty($hostname)) {
  4006. $hostname_rules = get_records_sql($db,
  4007. "SELECT * FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  4008. );
  4009. foreach ($hostname_rules as $row) {
  4010. if (!empty($row['rule'])) {
  4011. // Добавляем делимитеры к регулярному выражению, если их нет
  4012. $pattern = $row['rule'];
  4013. if (@preg_match($pattern, '') === false) {
  4014. // Если шаблон некорректен, пропускаем
  4015. continue;
  4016. }
  4017. if (preg_match($pattern, $hostname)) {
  4018. $result['user_id'] = (int)$row['user_id'];
  4019. return $result;
  4020. }
  4021. }
  4022. }
  4023. }
  4024. // === Правила для OU ===
  4025. // IP правила для OU (rule_type = 1)
  4026. if (!empty($ip)) {
  4027. $t_rules = get_records_sql($db,
  4028. "SELECT * FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  4029. );
  4030. foreach ($t_rules as $row) {
  4031. if (!empty($row['rule']) && is_subnet_aton($row['rule'], $ip_aton)) {
  4032. $result['ou_id'] = (int)$row['ou_id'];
  4033. return $result;
  4034. }
  4035. }
  4036. }
  4037. // MAC правила для OU (rule_type = 2)
  4038. if (!empty($mac)) {
  4039. $mac_simplified = mac_simplify($mac);
  4040. $mac_rules = get_records_sql($db,
  4041. "SELECT * FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  4042. );
  4043. foreach ($mac_rules as $row) {
  4044. if (!empty($row['rule'])) {
  4045. $pattern = '/' . preg_quote(mac_simplify($row['rule']), '/') . '/';
  4046. if (preg_match($pattern, $mac_simplified)) {
  4047. $result['ou_id'] = (int)$row['ou_id'];
  4048. return $result;
  4049. }
  4050. }
  4051. }
  4052. }
  4053. // Hostname правила для OU (rule_type = 3)
  4054. if (!empty($hostname)) {
  4055. $hostname_rules = get_records_sql($db,
  4056. "SELECT * FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  4057. );
  4058. foreach ($hostname_rules as $row) {
  4059. if (!empty($row['rule'])) {
  4060. $pattern = $row['rule'];
  4061. if (@preg_match($pattern, '') === false) {
  4062. continue;
  4063. }
  4064. if (preg_match($pattern, $hostname)) {
  4065. $result['ou_id'] = (int)$row['ou_id'];
  4066. return $result;
  4067. }
  4068. }
  4069. }
  4070. }
  4071. // Значение по умолчанию
  4072. if (empty($result['ou_id'])) {
  4073. $result['ou_id'] = get_const('default_user_ou_id');
  4074. }
  4075. return $result;
  4076. }
  4077. function get_subnet_range($db, $subnet_id)
  4078. {
  4079. if (empty($subnet_id)) {
  4080. return null;
  4081. }
  4082. $t_option = get_record_sql($db,
  4083. "SELECT ip_int_start, ip_int_stop FROM subnets WHERE id = ?",
  4084. [(int)$subnet_id]
  4085. );
  4086. if (empty($t_option)) {
  4087. return null;
  4088. }
  4089. return [
  4090. 'start' => isset($t_option['ip_int_start']) ? (int)$t_option['ip_int_start'] : 0,
  4091. 'stop' => isset($t_option['ip_int_stop']) ? (int)$t_option['ip_int_stop'] : 0
  4092. ];
  4093. }
  4094. function int_between($value, $start, $end)
  4095. {
  4096. return in_array($value, range($start, $end));
  4097. }
  4098. function is_gray_network($ip)
  4099. {
  4100. if (empty($ip)) {
  4101. return 0;
  4102. }
  4103. $ip_aton = ip2long($ip);
  4104. $gray_nets = array('10.0.0.0/8', '192.168.0.0/16', '172.16.0.0/12', '100.64.0.0/10');
  4105. foreach ($gray_nets as &$net) {
  4106. $net_cidr = cidrToRange($net);
  4107. if (int_between($ip_aton, ip2long($net_cidr[0]), ip2long($net_cidr[1]))) {
  4108. return $net;
  4109. }
  4110. }
  4111. return 0;
  4112. }
  4113. function is_hotspot($db, $ip)
  4114. {
  4115. if (empty($ip)) {
  4116. return false;
  4117. }
  4118. $ip_aton = ip2long($ip);
  4119. if ($ip_aton === false) {
  4120. LOG_DEBUG($db, "Invalid IP address: $ip");
  4121. return false;
  4122. }
  4123. LOG_DEBUG($db, "Check hotspot network for ip: $ip");
  4124. $t_option = get_records_sql($db, "SELECT subnet, ip_int_start, ip_int_stop FROM subnets WHERE hotspot = 1");
  4125. foreach ($t_option as $row) {
  4126. if ($ip_aton >= (int)$row['ip_int_start'] && $ip_aton <= (int)$row['ip_int_stop']) {
  4127. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in hotspot network " . $row['subnet'] . ": [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  4128. return true;
  4129. }
  4130. }
  4131. LOG_DEBUG($db, "ip $ip not found in hotspot network!");
  4132. return false;
  4133. }
  4134. function is_office($db, $ip)
  4135. {
  4136. if (empty($ip)) {
  4137. return false;
  4138. }
  4139. $ip_aton = ip2long($ip);
  4140. if ($ip_aton === false) {
  4141. LOG_DEBUG($db, "Invalid IP address: $ip");
  4142. return false;
  4143. }
  4144. LOG_DEBUG($db, "Check office network for ip: $ip");
  4145. $t_option = get_records_sql($db, "SELECT subnet, ip_int_start, ip_int_stop FROM subnets WHERE office = 1");
  4146. foreach ($t_option as $row) {
  4147. if ($ip_aton >= (int)$row['ip_int_start'] && $ip_aton <= (int)$row['ip_int_stop']) {
  4148. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in office network " . $row['subnet'] . ": [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  4149. return true;
  4150. }
  4151. }
  4152. LOG_DEBUG($db, "ip $ip not found in office network!");
  4153. return false;
  4154. }
  4155. function get_office_subnet($db, $ip)
  4156. {
  4157. if (empty($ip)) {
  4158. return null;
  4159. }
  4160. $ip_aton = ip2long($ip);
  4161. if ($ip_aton === false) {
  4162. LOG_DEBUG($db, "Invalid IP address: $ip");
  4163. return null;
  4164. }
  4165. LOG_DEBUG($db, "Check office network for ip: $ip");
  4166. $subnets = get_records_sql($db, 'SELECT * FROM subnets WHERE office = 1');
  4167. foreach ($subnets as $row) {
  4168. if ($ip_aton >= (int)$row['ip_int_start'] && $ip_aton <= (int)$row['ip_int_stop']) {
  4169. LOG_DEBUG($db, "ip: $ip [$ip_aton] found in office {$row['subnet']}: [" . $row['ip_int_start'] . ".." . $row['ip_int_stop'] . "]");
  4170. return $row;
  4171. }
  4172. }
  4173. LOG_DEBUG($db, "ip $ip not found in office network!");
  4174. return null;
  4175. }
  4176. function get_notify_subnet($db, $ip)
  4177. {
  4178. if (empty($ip)) {
  4179. return 0;
  4180. }
  4181. $office_subnet = get_office_subnet($db, $ip);
  4182. if ($office_subnet && isset($office_subnet['notify'])) {
  4183. return (int)$office_subnet['notify'];
  4184. }
  4185. return 0;
  4186. }
  4187. function is_our_network($db, $ip)
  4188. {
  4189. if (!isset($ip)) {
  4190. return 0;
  4191. }
  4192. if (is_hotspot($db, $ip)) {
  4193. return 1;
  4194. }
  4195. if (is_office($db, $ip)) {
  4196. return 1;
  4197. }
  4198. return 0;
  4199. }
  4200. function get_const($const_name)
  4201. {
  4202. global $config;
  4203. if (isset($config[$const_name])) {
  4204. return $config[$const_name];
  4205. }
  4206. return NULL;
  4207. }
  4208. function get_eye_version($db)
  4209. {
  4210. $v_table = get_record_sql($db, "SELECT version FROM version");
  4211. if (!empty($v_table)) {
  4212. return $v_table['version'];
  4213. }
  4214. return NULL;
  4215. }
  4216. function getNotifyFlags(): array {
  4217. return [
  4218. WEB_NOTIFY_NONE => NOTIFY_NONE,
  4219. WEB_NOTIFY_CREATE => NOTIFY_CREATE,
  4220. WEB_NOTIFY_UPDATE => NOTIFY_UPDATE,
  4221. WEB_NOTIFY_DELETE => NOTIFY_DELETE,
  4222. ];
  4223. }
  4224. function getNotifyLabels(): array {
  4225. return [
  4226. NOTIFY_NONE => WEB_NOTIFY_NONE,
  4227. NOTIFY_CREATE => WEB_NOTIFY_CREATE,
  4228. NOTIFY_UPDATE => WEB_NOTIFY_UPDATE,
  4229. NOTIFY_DELETE => WEB_NOTIFY_DELETE,
  4230. ];
  4231. }
  4232. function printFlagsByFirstLetter(int $flags): string {
  4233. if ($flags === 0) {
  4234. return 'x';
  4235. }
  4236. $flagLabels = getNotifyLabels();
  4237. $activeLetters = [];
  4238. $fullLabels = [];
  4239. foreach ($flagLabels as $flagValue => $label) {
  4240. if ($flagValue === 0) continue;
  4241. if (($flags & $flagValue) === $flagValue) {
  4242. $firstLetter = mb_substr($label, 0, 1, 'UTF-8');
  4243. $activeLetters[] = $firstLetter;
  4244. $fullLabels[] = $label;
  4245. }
  4246. }
  4247. sort($activeLetters);
  4248. $letters = implode('', $activeLetters);
  4249. $tooltipText = implode(', ', $fullLabels);
  4250. return '<span title="' . htmlspecialchars($tooltipText) . '">' . htmlspecialchars($letters) . '</span>';
  4251. }
  4252. function renderNotifyCombobox(string $name, int $selectedFlags = 0, array $attributes = []): string {
  4253. $labels = getNotifyLabels();
  4254. $flags = getNotifyFlags();
  4255. // Собираем атрибуты
  4256. $attrString = '';
  4257. foreach ($attributes as $key => $value) {
  4258. $attrString .= ' ' . htmlspecialchars($key) . '="' . htmlspecialchars($value) . '"';
  4259. }
  4260. // Предопределенные комбинации с читаемыми названиями
  4261. $combinations = [
  4262. NOTIFY_NONE => $labels[NOTIFY_NONE],
  4263. NOTIFY_CREATE => $labels[NOTIFY_CREATE],
  4264. NOTIFY_UPDATE => $labels[NOTIFY_UPDATE],
  4265. NOTIFY_DELETE => $labels[NOTIFY_DELETE],
  4266. NOTIFY_CREATE | NOTIFY_UPDATE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_UPDATE],
  4267. NOTIFY_CREATE | NOTIFY_DELETE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_DELETE],
  4268. NOTIFY_UPDATE | NOTIFY_DELETE => $labels[NOTIFY_UPDATE] . ' + ' . $labels[NOTIFY_DELETE],
  4269. NOTIFY_CREATE | NOTIFY_UPDATE | NOTIFY_DELETE => $labels[NOTIFY_CREATE] . ' + ' . $labels[NOTIFY_UPDATE] . ' + ' . $labels[NOTIFY_DELETE],
  4270. ];
  4271. $html = '<select name="' . htmlspecialchars($name) . '"' . $attrString . '>';
  4272. foreach ($combinations as $value => $label) {
  4273. $isSelected = ($selectedFlags === $value);
  4274. $selected = $isSelected ? ' selected' : '';
  4275. $html .= '<option value="' . $value . '"' . $selected . '>'
  4276. . htmlspecialchars($label)
  4277. . '</option>';
  4278. }
  4279. $html .= '</select>';
  4280. return $html;
  4281. }
  4282. /**
  4283. * Проверяет, установлен ли флаг создания
  4284. */
  4285. function isNotifyCreate(int $flags): bool {
  4286. return ($flags & NOTIFY_CREATE) === NOTIFY_CREATE;
  4287. }
  4288. /**
  4289. * Проверяет, установлен ли флаг изменения
  4290. */
  4291. function isNotifyUpdate(int $flags): bool {
  4292. return ($flags & NOTIFY_UPDATE) === NOTIFY_UPDATE;
  4293. }
  4294. /**
  4295. * Проверяет, установлен ли флаг удаления
  4296. */
  4297. function isNotifyDelete(int $flags): bool {
  4298. return ($flags & NOTIFY_DELETE) === NOTIFY_DELETE;
  4299. }
  4300. /**
  4301. * Проверяет, отключены ли все уведомления
  4302. */
  4303. function isNotifyNone(int $flags): bool {
  4304. return $flags === NOTIFY_NONE;
  4305. }
  4306. /**
  4307. * Проверяет, установлен ли конкретный флаг
  4308. */
  4309. function hasNotifyFlag(int $flags, int $flagToCheck): bool {
  4310. return ($flags & $flagToCheck) === $flagToCheck;
  4311. }
  4312. /**
  4313. * Устанавливает флаг(и)
  4314. */
  4315. function setNotifyFlag(int &$flags, int $flagToSet): void {
  4316. $flags |= $flagToSet;
  4317. }
  4318. /**
  4319. * Снимает флаг(и)
  4320. */
  4321. function unsetNotifyFlag(int &$flags, int $flagToUnset): void {
  4322. $flags &= ~$flagToUnset;
  4323. }
  4324. /**
  4325. * Преобразует массив выбранных значений в битовую маску
  4326. */
  4327. function arrayToNotifyFlags(array $selectedValues): int {
  4328. $flags = NOTIFY_NONE;
  4329. foreach ($selectedValues as $value) {
  4330. $flags |= (int)$value;
  4331. }
  4332. return $flags;
  4333. }
  4334. /**
  4335. * Проверяет, является ли OU системным (используется по умолчанию для пользователей или хотспотов)
  4336. *
  4337. * @param PDO $db
  4338. * @param int $ou_id
  4339. * @return bool
  4340. */
  4341. function is_system_ou($db, $ou_id = null) {
  4342. if (empty($ou_id) || !is_numeric($ou_id) || $ou_id <= 0) {
  4343. return false;
  4344. }
  4345. $sql = "SELECT 1 FROM ou WHERE id = ? AND (default_users = 1 OR default_hotspot = 1)";
  4346. return !empty(get_record_sql($db, $sql, [$ou_id]));
  4347. }
  4348. $config["org_name"] = get_option($db_link, 32);
  4349. $config["version"] = get_eye_version($db_link);
  4350. $config["KB"] = get_option($db_link, 1);
  4351. if ($config["KB"] == 0) {
  4352. $config["KB"] = 1000;
  4353. }
  4354. if ($config["KB"] == 1) {
  4355. $config["KB"] = 1024;
  4356. }
  4357. $config["debug"] = get_option($db_link, 34);
  4358. $config["log_level"] = get_option($db_link, 53);
  4359. if ($config["debug"]) {
  4360. $config["log_level"] = 255;
  4361. }
  4362. $config["send_email"] = get_option($db_link, 51);
  4363. $config["admin_email"] = get_option($db_link, 21);
  4364. $config["sender_email"] = get_option($db_link, 52);
  4365. $config["snmp_default_version"] = get_option($db_link, 9);
  4366. $config["snmp_default_community"] = get_option($db_link, 11);
  4367. $config["auto_mac_rule"] = get_option($db_link, 64);
  4368. $config["traffic_ipstat_history"] = get_option($db_link, 56);
  4369. $config["cacti_url"] = rtrim(get_option($db_link, 58), '/');
  4370. if (preg_match('/127.0.0.1/', $config["cacti_url"])) {
  4371. $config["cacti_url"] = NULL;
  4372. }
  4373. $config["nagios_url"] = rtrim(get_option($db_link, 57), '/') . '/cgi-bin/';
  4374. if (preg_match('/127.0.0.1/', $config["nagios_url"])) {
  4375. $config["nagios_url"] = NULL;
  4376. }
  4377. $config["torrus_url"] = rtrim(get_option($db_link, 59), '/') . '?nodeid=if//HOST_IP//IF_NAME////inoutbps';
  4378. if (preg_match('/127.0.0.1/', $config["torrus_url"])) {
  4379. $config["torrus_url"] = NULL;
  4380. }
  4381. $config["dns_server"] = get_option($db_link, 3);
  4382. $config["dns_server_type"] = get_option($db_link, 70);
  4383. $ou = get_record_sql($db_link, "SELECT id FROM ou WHERE default_users = 1");
  4384. if (empty($ou)) {
  4385. $config["default_user_ou_id"] = 0;
  4386. } else {
  4387. $config["default_user_ou_id"] = $ou['id'];
  4388. }
  4389. $ou = get_record_sql($db_link, "SELECT id FROM ou WHERE default_hotspot=1");
  4390. if (empty($ou)) {
  4391. $config["default_hotspot_ou_id"] = $config["default_user_ou_id"];
  4392. } else {
  4393. $config["default_hotspot_ou_id"] = $ou['id'];
  4394. }
  4395. $config["init"] = 1;
  4396. clean_dns_cache($db_link);
  4397. //clean_unreferensed_rules($db_link);
  4398. $config["debug"] = 1;