common.php 162 KB

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