common.php 154 KB

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