common.php 153 KB

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