common.php 163 KB

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