common.php 153 KB

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