common.php 157 KB

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