common.php 155 KB

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