1
0

common.php 151 KB

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