common.php 153 KB

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