common.php 158 KB

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