common.php 151 KB

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