1
0

common.php 154 KB

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