common.php 153 KB

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