1
0

common.php 158 KB

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