common.php 154 KB

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