common.php 151 KB

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